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

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ;

OOPS Concept in Java : ENCAPSULATION

OOPS Concept in Java : ENCAPSULATION   This OOPS concept can be used to make things simpler in case of software development . Main purpose of this concept is to hide the properties of any class and give access to fetch and modified based on business criteria.  A simple example can be a POJO ( Plain Old Java Object) in which all the properties of a class can be private and through getter and setter method of properties we can fetch and update the properties of Object. So instead of having direct access to properties we have created 2 methods to make the CLASS things encapsulated in single unit while access to it is via 2 public methods.   Just consider we have requirement that once the object is created its value should not be changed then simplest way to achieve this  can be done by just removing setter method and we will keep only getter methods to access Object properties . In this case after Object creation whatever the value of Object properties has been initialised it will b

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If Object is of PARENT