DEV Community

Md Shahriar
Md Shahriar

Posted on

Understanding the Spring Security Architecture

Securing applications the proper way has never been more crucial. While there are many options to secure yours. Let me walk you through the Spring Security architecture to help you understand why this could be your go-to framework.

A Look at the components involved

At first, the client sends the HTTP request to the server, which must go through a filter chain called the Security Filter Chain. The filter chain has multiple layers, but we'll focus on just the UsernamePasswordAuthenticationFilter (which is part of the chain). Spring Security's default setting is to use a login form where you'll get a randomly generated password on your terminal, which you need to use to log in.

After you provide your credentials, UsernamePasswordAuthenticationToken is generated with the username and password. This token is passed on to the AuthenticationManager (which is responsible for managing the authentication). It is then passed to one of it's AuthenticationProviders beans(DaoAuthenticationProvider is widely used). The provider handles the authentication logic by verifying the user credentials against a database.

Authentication logic can be complex and requires a class to help fetch user details stored in the database. For that, UserDetailsService is used, which implements the UserDetails interface to load the data.

When the UsernamePasswordAuthenticationToken is validated, it is populated with additional data (for example, the user's granted authorities) and returned to the AuthenticationManager, which then places it in the SecurityContext, wrapped around the SecurityContextHolder. If the application is session-based, the SecurityContext is stored in the HTTP session.

When the client logs out, the authentication object is cleared from the SecurityContextHolder.

Point to be Noted:

When the session is stateless (for example, when using JWT tokens), the security measures are handled differently. Most of the authentication process is similar except the fact that stateless authentication doesn't rely on server side sessions.

Top comments (0)