top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

JWT based Security Implementation for Rolebased Applications utilizing Spring Security!..

JWT - JSON Web Token is a safe way to implement security in Applications. Spring Security is a powerful and highly customizable authentication and access-control framework for Java applications. We utilize both of them in this implementation.


Step 1: Password Encryption :

We used BCrypt Password Encoder to encrypt the password and store in DB.

Best part is , you cant decrypt the password.

How does it work then ? the password user enters while logging will be encrypted and it wud be compared with encrypted password in DB.

When the User resets their password, it would be bcrypted and stored.


Step2 : Utilize Spring Security

When user logsin with their Username, password credentials, these would be verified against User Credentials in DB. This is done by Custom UserService implementing UserDetailsService Interface.

We will be overriding loadUserByUserName() and provide this logic here. We need to build UserDetails Object here as well. Please note UserDetails is an Interface in Spring security. You need to provide implementation class for that.

                	org.springframework.security.core.userdetails.UserDetailsService;                 

We wud be storing this UserDetails Object in UserCache. You could see @Cacheable annotation.


Step 3 : Configuring Security

We need to have a Security Config class.

We use Spring Boot 3.2.2. WebSecurityConfigAdapter is deprecated.

With WebSecurityConfigurerAdapter deprecated, the preferred approach is to configure the filter chain using SecurityFilterChain bean and functional-style configuration. [ You provide a custom method which returns SecurityFilterChain Object. ]

Start the class by annotating with @Configuration @EnableWebSecurity

You are declaring and registering BCryptPasswordEncoder Object, UserDetailsService Object , JWTTokenFilter Object and so;

We can configure CORS, CSRS as per the need of the application.

You are specifying open endpoints and ask Spring security to allow them without authentication.

"/auth/token" is one such open endpoint.


Key Components
  1. HttpSecurity: Used to configure web-based security for HTTP requests.

  2. SecurityFilterChain: A bean that defines the filter chain for Spring Security.

  3. UserDetailsService: Service for loading user-specific data.

  4. PasswordEncoder: For encoding passwords.

  5. AuthenticationManager: Manages authentication.

Step 4 : Writing your Filter

One of the key components of Spring Security is the filter chain.

The Spring Security Filter Chain is a sequence of filters that the framework uses to process security-related tasks in a web application. Each filter in the chain is responsible for a specific aspect of security, such as authentication, authorization, and CSRF protection.


Key Components and Flow

Security Filters: These filters intercept incoming HTTP requests and perform various security checks and operations. Some common filters include:

  • Authentication Filter: Processes login attempts and establishes the authentication of the user.

  • Authorization Filter: Checks if the authenticated user has the necessary permissions to access the requested resource.

  • CSRF Filter: Protects against Cross-Site Request Forgery attacks.

  • Session Management Filter: Manages session-related security concerns, such as session fixation attacks.

When you add a custom filter in Filter chain, you need to specify before which filter or after which specific filter , your filter should be invoked.

.addFilterBefore( authTokenFilter, UsernamePasswordAuthenticationFilter.class)     

This filter would be called for each request.

We would parse the token and if its not valid, it would throw 401 error.

If its a valid token, UserDetails Object wud be pulled from cache, if its available in cache else we would get it from DB. A UserNamePasswordAuthenticationToken Object would be created from this and set it in SecurityContextHolder.

Spring Security would allow APIs, based on the roles in Authentication Object.

SecurityContextHolder.getContext().setAuthentication(authentication);

Authentication represents the currently logged in Users Credentials and Roles.


Step 5 :

Spring security handles Authorization using Annotations like @PreAuthorize, @PostAuthorize, @RolesAllowed

Here it is implemented with @PreAuthorize

createBatch API could be accessed only when User has Admin access.


Step 6 : Logout

During logout we would, remove the UserDetails Object from Cache.

Instruct the front end to remove the JWT Token stored in their end.

34 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page