Spring Security: How it works internally

Reading Time: 5 minutes

Definition

Spring Security is a framework provided by Spring that helps to customize an access and authentication process. It plays a very crucial role in terms of securing the applications.

Spring Security, mainly focuses on authentication and authorization to provide all benefits to java applications. It is very helpful and provides an easy approach to apply in real projects. And, permits to do custom modifications in real projects.

Benefits/Features

  • Supports authentication and authorization processes comprehensively and extensively.
  • Prevents from cross-site forgery, session fixation, clickjacking, etc.
  • Integrates the Servlet API.
  • Provides integration with Spring Web MVC optionally.

Workflow: How the user’s credentials verified and managed

This workflow represents the work cycle of the user’s credentials once provided by the user. It shows how the user’s credentials are verified and revolve around inside the Spring Security.

Diagram: The journey of user’s credentials in the Spring Security

Authentication Filter

Authentication Filter is the filter that intercepts the requests. And once it intercepts those requests it would try to convert the authentication details. As a result, we are receiving the details from the user like username and password into the authentication object.

Authentication object: It is a base object that is responsible to validate the user’s credentials.

Authentcation Manager:

Authentication Manager is the place where it will identify which is a correspondent authentication provider that request has to go. And, the user does not follow many processes to validate the credentials, as he/she may use the database to validate user credentials. Or he/she may use LDAP or he/she may use possible providers that the system may have Authentication Manager.

It is responsible to identify the most appropriate authentication provider and send the user’s request once the authentication provider receives the request.

Authentication Provider

Authentication Provider implements all the logic of security validation inside it. Spring Security provides some features to customize (authentication of the endpoints as per the choice) the requests:

  • Provides custom authentication to the endpoints:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> {
        ((AuthorizedUrl)requests.antMatchers("/endpoint1")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint2")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint3")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint4")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint5")).permitAll();
        ((AuthorizedUrl)requests.antMatchers("/endpoint6")).permitAll();
    });
    http.formLogin();
    http.httpBasic();
}
  • Provides authentication to all the endpoints:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> {
        ((AuthorizedUrl)requests.antMatchers("/endpoint1")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint2")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint3")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint4")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint5")).permitAll();
        ((AuthorizedUrl)requests.antMatchers("/endpoint6")).permitAll();
    });
    http.formLogin();
    http.httpBasic();

    http.authorizeRequests((requests) -> {
        ((AuthorizedUrl)requests.anyRequest()).authenticated();

    });
    http.formLogin();
    http.httpBasic();
}
  • Unauthenticates all the endpoints:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> {
        ((AuthorizedUrl)requests.antMatchers("/endpoint1")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint2")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint3")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint4")).authenticated();
        ((AuthorizedUrl)requests.antMatchers("/endpoint5")).permitAll();
        ((AuthorizedUrl)requests.antMatchers("/endpoint6")).permitAll();
    });
    http.formLogin();
    http.httpBasic();

    http.authorizeRequests((requests) -> {
        ((AuthorizedUrl)requests.anyRequest()).permitAll();

    });
    http.formLogin();
    http.httpBasic();
}

And it uses two interfaces internally:

User Details Service (Interface): This is an interface that holds the user schema, and shows how the user details should look like username, password, MFA, etc.

Password Encoder (Interface): This is an interface that helps to encrypt, encode, and decrypt the user’s passwords while evaluating the security. And, the flow backs to Authentication Manager, whether the provided input (authentication object) is valid or not.

The authentication object is sent from the Authentication filter internally, whether the user is a valid authenticated user or not, and what are the roles and authorities that are associated with it.

Inside the authentication, the object provided by Authentication Filter is populated from Authentication Provider and Authentication Manager.

Afterward, the Authentication Filter passes the authentication object to security which saves the user’s details that will be stored inside the container.

Lastly, the token gets generated, and the application will hold the token, which will be stored in the Security Context interface.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("admin")
            .and()
            .withUser("user").password("user").authorities("read")
            .and()
            .passwordEncoder(NoOpPasswordEncoder.getInstance());
}

Security Context

Security Context is a place where user can see his/her data once he/she authenticates themself, and identify whether he/she is a valid user or not. And this information of the user will automatically store inside the Security Context and responds back to the browser.

For the second time, attempts to pass the same security information and same flow will not execute further as the user’s credentials are validated already.

Workflow: Let’s understand the management cycle of a user in Spring Security

This workflow represents the management cycle of the user. It shows how the information of the user like username, password, roles, authorities store and manage inside the Spring Security.

Diagram: How the user got managed thoroughly in Spring Security

User Details (Interface)

User Details interface is an interface that helps to identify the username, password, roles, and authorities of the user. It is also responsible to inspect the validity/expiry of the user’s account. It is a contract or schema or blueprints maintained by the spring security framework. And also represents an actual user who is trying to access our application.

If the user is good to go with the default implementation provided by the spring framework itself, can go ahead and use the User (class), which implements this user details interface, and how all the implementation of these abstract methods.

User Details Manager (Interface)

User Details Manager extends UserDetailsService (implementation class) which means a single abstract method will also be present in this interface. Therefore, those who want to implement this user details manager have to provide concrete implementation for all these methods.

As a result, create a user, and as you can expect the argument of this method is user details.

In Memory User Details Manager (Class)

Memory User Details Manager is the implementation class that helps to maintain all the users, who can load the user details, authentication details, authorities, everything from the memory itself, which will store and set the Spring Context.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();

        UserDetails userOne = User.withUsername("admin").password("admin").authorities("admin").build();
        UserDetails userTwo = User.withUsername("user").password("user").authorities("read").build();

        userDetailsService.createUser(userOne);
        userDetailsService.createUser(userTwo);
        auth.userDetailsService(userDetailsService);
}

JDBC User Details Manager (Class)

JDBC User Details Manager is the most famous implementation provided by spring security. This is the production-grade ready implementation, which means if you provide the data source details of MySQL, Oracle, or any database, this JDBC user details manager has all the code related to loading the user details, maintaining them, changing the passwords.

LDAP User Details Manager (Class)

LDAP User Details Manager is the implementation class that leverages the LDAP server for authorization and authentication purposes.

User is the default implementation provided by the spring security that occurs to the user details interface schema.

Reference

For detailed information on Security Security, please click here.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading