How Authentication Works In Spring Security

In this Post of How Authentication Works In Spring Security , we will cover Authentication Flow in Spring Security . This is going to be a long article as we will be discussing Spring Security Authentication Full Flow . Do not Forget to Check the Video Link below with detailed explanation .

Spring Security provides comprehensive security services for J2EE-based enterprise software applications. People use Spring Security for many reasons, but most are drawn to the project after finding the security features of J2EE’s Servlet Specification or EJB Specification lack the depth required for typical enterprise application scenarios.

Learn

  1. How to Integrate Oauth2 in Spring Applications
  2. Filter Chain and Delegating Filter Chain Proxy

Understanding Spring Security flow is one of the most Important concepts for starting off in Spring Security . We are going to study the complete architecture of spring security in detail.

Spring Security Works on Three Core Principles or Steps :-

  1. Authentication
  2. Authorization
  3. Exception handling

We Will See How Spring Initiates and Starts the Whole Authentication Process , but lets discuss Spring Authentication Flow , then we Will deep dive in upcoming Posts.

How Authentication Works In Spring Security 

Considering the design of spring security , Spring  Security basically is a chain of Servlet filters written for various purposes. Each of those filters are meant to do some specific task .So there are different authentication mechanisms provided in Spring such as Http Basic , Form based login , Ouath1 etc .

All these mechanisms are handled by Specific Filters Which extends AbstractAuthenticationProcessingFilter .  So all requests are handle by this Filter and in the Whole Post we will name it as Authentication Filter.

Now the basics of spring security is Basically these Filters , We need to understand the purpose of it . Have a look at different Filters and its Use cases .

How HTTP Basic Authentication Works In Spring Security

Once a Servlet request for HttpBasic Authentication reaches Spring Security , Authentication Filter Picks it up and tries to  decode Http Basic Headers . It then checks if Authentication is required or not . If authentication is required It Creates an  instance of UserNamepasswordAuthenticationToken  with username and token  and sets isAuthenticated(false) .  This token is  then passed to AuthenticationManager  as shown in diagram below . 

SpringSecurityAuthenticationFlow
Authentication Manager

 How AuthenticationManager authenticates that token we will see in a while .Now the Authenticated value in this step is Still False till UserNamePassWordAuthenticationToken is passed to AuthenticationManager . So Once AuthenticationManager Processes the Request  with that Token Object  , the status of Authentication value is Changed to true in case of Successful authentication  as shown below else AuthenticationException is thrown.

authentication object spring security
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
						username, tokens[1]);				
Authentication authResult = authenticationManager.authenticate(authRequest);

How Authentication Manager handles Authentication In Spring Security

Spring Authentication manager is Responsible for Handling Authentication , using different Authentication providers . We can also use a custom authentication Provider like Databse , LDAP etc. So the Sole responsibilty of AuthenticationProvider is to return an Authentication instance with Principal Object and Granted Authorities Populated .

Have a look at AuthenticationManager Source Code :-

package org.springframework.security.authentication;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public interface AuthenticationManager {
    Authentication authenticate(Authentication authentication) throwsAuthenticationException;
}
  • Once a user sends a request it  reaches the right authentication filter based on the authentication mechanism used.
  • Now it extract the given credentials from the request and then using the supplied values UsernamePasswordAuthenticationToken is  created( the authentication object).Then  it calls ‘authenticate’ method of the Authentication Manager.
  • The request then passes to Authentication Provider and the Authentication Provider contains an implementation of UserDetailsService.
  • Spring loads the user information in UserDetailsService  by calling loadbyuserName and compares the username/password combination with the credentials supplied at login.

If the user is valid then Authentication Manger creates UsernamePasswordAuthenticationToken  instance with follwing Constructor  , setting authenticated =true .

public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		this.credentials = credentials;
		super.setAuthenticated(true); // must use super, as we override
	}

UserNamePasswordAuthenticationToken is the Authentication object which is passed to authenticate method of Authentication Manager. Have a look how Authentication interface in Spring looks like

package org.springframework.security.core;

import java.io.Serializable;
import java.security.Principal;
import java.util.Collection;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
public interface Authentication extends Principal, Serializable {
	Collection<? extends GrantedAuthority> getAuthorities();
	Object getCredentials();
	Object getDetails();
	Object getPrincipal();
	boolean isAuthenticated();
	void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

Now this Authentication object  is then passed to Authentication Filter . Authentication Filter Sets the Authentication Object Containing Principal and Granted Authorities in Security Context  as Show below extending the above diagram.

AuthenticationFilter-and-SecurityContext

How to Configure Multiple Authentication Providers In Spring Security

We can configure multiple AuthenticationProviders in Spring Security , that will return Authentication Object if any of them is sucessful .Have a look at Configuring Custom Authentication Providers in spring Security .

Spring Security provides a number of AuthenticationProvider implementations,

  1. Dao AuthenticationProvider
  2. Cas AuthenticationProvider
  3. X509  AuthenticationProvider
  4. Jaas AuthenticationProvider
  5. Ldap AuthenticationProvider

In next Post We will See How We Can Create Custom Authentication Providers in Spring Security  and Explain the Authorization Flow .

Now that You have understood the Http-Basic Authentication mechanism in Spring , its same in case of other Authentication Mechanisms in Spring Security . Please let me know in frugalisminds@gmail.com  with Post title in Subject if you have any Questions or clarifications .

Summarizing Authentication Flow Spring Security :-

  • Authentication Filter creates an Authentication Request and Passes to Authentication Manager.
  • Authentication Manager delegates the request to Authentication Provider
  • Authentication Provider calls User Details service loads the User Details and returns the Authenticated Principal.
  • Authentication Manager returns the Authenticated Object to Authentication Filter and Authentication Filter sets the Authentication object in Security Context .

Note :- If you think closely we don’t need an User Details Service as well , the only things that is needed to Authentication Provider is an Authentication object with Principal as any Object and Granted Authorities .

This is the beauty of Spring Framework , where you always have an option to customize stuff.

More Posts On Spring Security :-

FilterChainProxy and DelegatingFilterProxy Uses

Using Custom Authentication Provider Spring Security

Article Written and Published By :- Subrat Padhi .