Using Custom Authentication Provider Spring Security

custom Authentication Provider

Using Custom Authentication Provider Spring Security

In this post we are going to find out why we need Custom Authentication Provider in Spring Security . Why do we need to implement this .

If You have  followed previous post about Flow of Authentication in Spring Security .

Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled.

This occurs when the FilterChainProxy decides which filter chain a request should be passed through and also when the FilterSecurityInterceptor decides which security constraints apply to a request.

Once it reaches the right authentication filter based on the authentication mechanism used ,  it extract the given credentials  from the request and then using the supplied values it creates the authentication object.

The it calls 'authenticate' method of the AuthenticationManager.

Now once Authentication manager tries to authenticate the request it  passes through the authentication providers to authenticate the user.

All the Authentication Providers inside spring security framework implement this interface .

Have a look at the Authentication Provider interface below :-

Now As you know for Writing a Custom Authentication provider in Spring Security , you basically should create your own implementation .

But Wait , Lets find out Why do we need a Custom Authentication Provider in Your Spring based applications by example .

Use Cases When do You Need Custom Authentication Provider :-

Lets say you are using authentication services provided by some third party in the form of Jar or an API.

In that case you can use the Spring Security Custom Authentication Provider to validate the username and password using the API . Once the validation is successful  we create the Authentication object and return to Spring Security framework.

Lets Implement a Custom Authentication Provider In Spring Security , by implementing Authentication Provider interface .

Lets Configure Spring Boot First before Configuring Custom Authentication Provider .

Configure Spring Security Configuration for Custom Provider 

The above code registers a custom authentication provider and authorize users .Now lets define a Custom Authentication Provider

Code Explanation

In above code we have retrieved Username and password from the Authentication object . Once We retrieve the Authentication Object and Credentials , we are validating the username and password .

You can perform database based authentication , we have done a hard coded validation here .

Once user is valid we try and set GRANTED_AUTHORITY in list of String and return an UserDetails Object to the Caller an Authentication object . Instead of spring provided UserDetails , we can customize the User object set in principal and return .


Please enter your comment!
Please enter your name here