DEV Community

kishorek2511
kishorek2511

Posted on

Spring Security role based Authentication & Authorization Implementation with Spring Boot 3.0

Hello learners, here we are going to know about spring security implementation with spring boot. Spring security provides authentication, authorization, and protection against common attacks.

Image description

Authentication - Authentication is how we verify the identity of the user trying to access a particular resource, once authentication is performed we know the identity and can perform authorization.
Authorization - Authorization means giving permission to access particular resource/url.

Steps to Implement Spring Security

Step 1: Add Spring Security dependency in POM.XML

Image description

Step 2: Create a configuration class , add authentication and authorization methods.

Image description

@EnableWebSecurity provides default security configuration to our application.Default security activates both HTTP security filters and the security filter chain and applies basic authentication to our endpoints.

@Configuration tells Spring Boot to scan the class for bean definitions and register them with the application context.

authenticateProvider() method is used to store all the user deatils like username, password, roles.Spring Security contains DaoAuthenticationProvider class which contains userDetailsService and passwordEncoder.passwordEncoder() is used to encrypt the password and encrypted password is stored in DB.

SecutityFilterChain() method is to authorize the resources, here
.requestMatchers("/products/welcome","/products/new").permitAll() is to give access to all the users, any user can access those two urls.
requestMatchers("/products/**").authenticated() is to give access to authenticated users.

Step 3: Implement role based authorization

Image description

@PreAuthorize annotation is used to specify a expression that will be evaluated before the method is executed. If the expression evaluates to true, the method is executed otherwise, an AccessDeniedException is thrown.

The getAllProducts() method can only be executed by users with the ROLE_USER role, while the getProductById() method can be executed by users with the ROLE_ADMINrole.
Testing the implementation

Image description

Added the sample code to test the implementation.

Image description

After giving user credentials user can able to access the user endpoint
When user try to access Admin endpoint with user credential, error page will display

Image description

Top comments (0)