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.

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

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

@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

@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

Added the sample code to test the implementation.

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

原文链接:Spring Security role based Authentication & Authorization Implementation with Spring Boot 3.0

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
No matter when you start, it is important not to stop after the start.
无论你在什么时候开始,重要的是开始之后就不要停止
评论 抢沙发

请登录后发表评论

    暂无评论内容