Skip to main content

SECURITY IN SPRING BOOT : Authentication and Authorisation in Spring boot Application

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 .

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

   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>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
<version>2.3.3.RELEASE</version>
</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.

    @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.

Will request you to go through previous post of Spring Boot to understand it in more detail.

Comments

  1. This is a really authentic and informative blog. Share more posts like this.
    Benefits of Learning German
    German Study

    ReplyDelete
  2. Thanks for the Feedback, we will soon publishing more new content

    ReplyDelete
  3. Wynn casino opens in Las Vegas - FilmfileEurope
    Wynn'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

    ReplyDelete

Post a Comment

Popular posts from this blog

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control Java flight recording(JFR) help us to analyse and find the root cause of any slowness in our program along with CPU usage , hot methods and garbage collection , profiling etc. To visualise we need to feed .jfr file to JDK mission control present in JDK bin folder. After successful compilation , we should run the program with below option which will generate the .jfr and feed to mission control.   command :  j ava -XX:+UnlockCommercialFeatures -XX:+FlightRecorder  -XX:StartFlightRecording=duration=200s,filename=flight.jfr -cp ./out/ path-and-class-name Below are some example to understand how this JFR can be helpful. 1. Lets consider we have created a java program in which we have used LinkList to store the elements and in same program we are using contains method inside a for loop of 1 million , in this case each time this contains method will be called then 1 million records will be sc...