Skip to content

Authentication

The Spring Security framework defines main interface AuthenticationManager for various authentication strategies. There are some provided by framework, but you can implement your own AuthenticationManager. Recommendation for you is to first check if there is existing implementation and then decide to go for customization. You should always try to stick with standards.

Authentication Methods

  • Username and Password - how to authenticate with a username/password
  • OAuth 2.0 Login - OAuth 2.0 Log In with OpenID Connect and non-standard OAuth 2.0 Login (i.e. GitHub)
  • SAML 2.0 Login - SAML 2.0 Log In
  • Central Authentication Server (CAS) - Central Authentication Server (CAS) Support
  • Remember Me - How to remember a user past session expiration
  • JAAS Authentication - Authenticate with JAAS
  • OpenID - OpenID Authentication (not to be confused with OpenID Connect)
  • Pre-Authentication Scenarios - Authenticate with an external mechanism such as SiteMinder or Java EE security but still use Spring Security for authorization and protection against common exploits.
  • X509 Authentication - X509 Authentication

Authenticated Users

Users can be:

  • anonymous
  • fully-authenticated
  • remember-me authenticated

Main Components

public interface AuthenticationManager {

  Authentication authenticate(Authentication authentication)
    throws AuthenticationException;
}

The AuthenticationManager interface defines authenticate() method with the Authentication argument (holds principal to be authenticated). If Authentication fails, the runtime AuthenticationException is thrown. Usually the AuthenticationManager delegates the authentication logic to one or more providers of type AuthenticationProvider. There are providers which supports certain authentication method. So you can configure chain of providers for multifactor authentication (MFA) for instance.

public interface AuthenticationProvider {

    Authentication authenticate(Authentication authentication)
            throws AuthenticationException;

    boolean supports(Class<?> authentication);
}

One example of Authentication Providers one which retrieves principal details form data store as SQL database. The authentication object is typically in form of token as UsernamePasswordAuthenticationToken, JwtAuthenticationToken, and others.

You can plug-in custom AuthenticationProvider using AuthenticationManagerBuilder. For example like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
    private CustomAuthenticationProvider authProvider;

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = 
            http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(authProvider);
        return authenticationManagerBuilder.build();
    } 

    [...]
} 

Authentication object consists of:

  • principal - identifies the user. When authenticating with a username/password this is often an instance of UserDetails.
  • credentials - Often a password. In many cases this will be cleared after the user is authenticated to ensure it is not leaked.
  • authorities - the GrantedAuthority is high level permission the user is granted. A few examples are roles or scopes.

AuthenticationEntryPoint is used to send an HTTP response that requests credentials from a client.

SecurityFilterChain and Authentication

Flow diagram

diagram

  1. The browser sends GET request to backend Spring application without HTTP Basic Authentication data (Authorization HTTP header).
  2. Request is forwarded to the SecurityFilterChain by FilterChainProxy. The SecurityFilterChain is what you configure to stack several security filters responsible for request handling from security perspective.
  3. In some point the request is processed by the BasicAuthenticationFilter which participates on Authentication process. The BasicAuthenticationFilter does not find HTTP Authorization header in HTTP Request ,and it throws AuthenticationException. No further filter in chain is processed.
  4. AuthenticationException is handel by the BasicAuthenticationEntryPoint component, which adds WWW-Authenticate header into response.
  5. Browser processes response and renders default login form for User. User provides username and password and Browser sends the request again. This time with the HTTP Authorization: Basic token header.
  6. Request is forwarded to the SecurityFilterChain again.
  7. The BasicAuthenticationFilter finds requred Authorization header, extracts data from it, and creates UsernamePasswordAuthenticationToken. Token represents Authentiation which is sent to )AuthenticationManager_ for authentication.
  8. The UsernamePasswordAuthenticationToken which holds username and password in this case is received by the _ProviderManager, which is the default implementation of the AuthenticationManager. The ProviderManager maintains ordered set of Authentication Providers responsible for authentication logic.
  9. This time the DaoAuthenticationProvider receives token for authentication. Authentication provider authenticates by comparing received User's password (credential) with one stored in user repository.
  10. The Authentication provider usually uses the UserDetailService implementation to retrieve User detail from repository. There is InMemoryUserDetailsManager which maintians Users and Authorities in memory.
  11. Upon successful authentication, the BasicAuthenticationFilter creates SecurityContext with authenticated principal. If the token was not authenticated the error HTTP response 401 is created and returned.
  12. Now, the next filter in chain is executed. This typically involves AuthorizationFilter.
  13. Finally, the request is processed by underlying service layer and response travels back to client.
  14. Backend responeses with success including data.

Diagram from Spring Security documentation diagram


Read more: * https://docs.spring.io/spring-security/reference/servlet/authentication/index.html * Migration to 6.2: https://docs.spring.io/spring-security/ reference/migration/index.html