SECURITY IN SPRING BOOT : Authentication and Authorisation in Spring boot Application
In any application security is the most important aspect without this no application can be considered as standard application as it will have full exposure to hackers. Now to secure our application there are 2 important concept Authentication and Authorisation which we should know .
Authentication stands for authentication of the client from your request is coming and to do so we will receive unique username and password for that to validate the authenticity of client. If it passes through our authentication process and identified as valid client then we will proceed and allow to access our URI and resources.
Authorisation comes after authentication in which we will allow to access our resources based on type of client if client is an Admin then he will have full access , if client is Premium user then he will have access to all premium resources if client is guest or any other user type then he will have access to only some limited resources.
Now to implement Authentication and Authorisation below are the steps to be followed.
Step 1:
First we need to put dependency in our pom.xml file for spring security then apply the annotation @EnableWebSecurity on configuration class level .
This will restrict any call by Front controller directly, what is Front controller and flow of Spring i already explained in details in the post SPRING BOOT OVERVIEW , it applies filter using class called DelegatingFilterProxy (public class DelegatingFilterProxy extends GenericFilterBean)
In Spring boot we have a class called WebSecurityConfigurerAdapter, that we need to extend by our custom class responsible for implementing Security, WebSecurityConfigurerAdapter class has 2 configure method , one with the input param as HttpSecurity and other with input param as AuthenticationManagerBuilder
Authentication :
1. Configure method with input param as AuthenticationManagerBuilder will be used for Authentication , there are multiple option for Authentication as below, we can use any one to implement Authentication in our application.
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
auth.jdbcAuthentication();
auth.ldapAuthentication();
auth.userDetailsService(your customize service);
auth.authenticationProvider(authentication provider);
}
In below code we are using userDetailsService for Authentication and EmployeAuthentication is our customised userdetailsService which is taking a class EmployeeAuthentication as Parameter inside which we will have our authentication logic
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new EmployeeAuthentication());
}
EmployeeAuthentication.java inside which we have authentication logics, this class should return a object of UserDetails.User of type Principal this object will be used by spring SecurityContext to validate all the incoming request after successfully authentication for the first time.
Our customize UserDetails service should implement UserDerailsService Interface and override the method loadUserByUsername . For now i have hardcoded the username and password.
class EmployeeAuthentication implements UserDetailsService {
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return new User("user1",encoder.encode("12345678"), Collections.singleton(new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_NONUSER";
}
}));
}
}
SecurityContextHolder is the helper class which help SecurityContext to hold the object in ThreadLocal and validate every time using HttpSession.
You can also get the all the details of currently logged in user from following java line.
SecurityContextHolder.getContext().getAuthentication()
Authorisation :
Configure method with input param as HttpSecurity will be used for Authorisation using antmatcher
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/welcome/").permitAll()
.antMatchers("/home").authenticated()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasRole("USER")
.antMatchers("/other").hasAnyRole("GUEST","ADMIN","USER")
.anyRequest().authenticated()
.and().formLogin().defaultSuccessUrl("/home")
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and().exceptionHandling().accessDeniedPage("/accessDenied");
}
QUESTION : How do you implement OAuth2 in your spring boot application ?
Step 1 : Put the OAuth Dependency in pom.xml file of application so that respective jar will be downloaded and available to spring boot application.
<dependency>Step 2 : For OAuth2 login we don't need to override configure method of WebSecurityConfigurerAdapter with input param as AuthenticationManagerBuilder, only we need to override configure method with input param as HttpSecurity and inside this method we need informed Spring boot to do OAuth2 validation using below java line.
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().oauth2Login()
}
Now we also need to inform spring boot what type of Authorisation server it can be like Google, Facebook etc
For that we need client id and client secret in application.yml of our spring boot application, which we should have created before from portal of Google or Facebook and redirect URL should be same for unauthorised request.
OAuth using Google
Step 1:
URL to understand how to create client id :
https://developers.google.com/adwords/api/docs/guides/authentication
URL to create Client id :
https://console.cloud.google.com/apis/credentials
Step 2:
In Application.yml we need to give client id and client secret generated from Google.
spring.security.oauth2.client.registration.google.client-id=you client id
spring.security.oauth2.client.registration.google.client-secret=you client secret
By Default URL for OAuth in spring boot application will be:
URL for Google OAuth is : http://localhost:8080/login/oauth2/code/google
URL for Facebook OAuth is : http://localhost:8080/login/oauth2/code/facebook
Once both the steps are done you can try to access any URL of you application which will redirect to Gmail authentication page once you are authenticated you will have a token of authorisation and will be able to access all endpoints.
This is a really authentic and informative blog. Share more posts like this.
ReplyDeleteBenefits of Learning German
German Study
Thanks for the feedback
DeleteThanks for the Feedback, we will soon publishing more new content
ReplyDeleteWynn casino opens in Las Vegas - FilmfileEurope
ReplyDeleteWynn's 토토 사이트 first hotel casino in Las Vegas since opening its doors https://vannienailor4166blog.blogspot.com/ in 1996, Wynn worrione Las Vegas is the first hotel on the septcasino Strip to kadangpintar offer such a large selection of