The content of this article is about how to quickly implement Spring security permission authentication management (detailed steps). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Build the project
Let’s get started without further ado.
pom.xml:
The core dependencies of spring security are as follows
<!-- spring security --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> </dependency> <!-- spring security data --> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-data</artifactid> </dependency>
Configure the user main class: User and implement security’s UserDetails
Override several of its methods. The default configuration is false and needs to be changed to true.
#Configure UserService to implement the UserDetailsService interface and override the loadUserByUsername method.
This method is used during security login. The queried information must include user information and role information.
Create UserController, since we configured .antMatchers("/login","/register above ") allows access to only these two interfaces when not logged in.
When you are not logged in, accessing non-permitted interfaces will redirect you to login.
The effect is as follows:
After successful login, access /users
We have easily implemented login authorization, so that our API is protected.
If you need to specify the access permissions for different roles, just add an annotation to the Controller.
@PreAuthorize("hasRole('ROLE_ADMIN')")//Requires administrator identity
@PreAuthorize("hasRole('ROLE_USER')")//Requires user identity
Through the above brief description, we have completed the integration of Spring boot mybatis with Spring security.
Due to limited time, I will only give a brief description in the article. Visit my Github to view the complete Demo.
url: https://github.com/admin79/SecurityDemo
The above is the detailed content of How to quickly implement Spring security permission authentication management (detailed steps). For more information, please follow other related articles on the PHP Chinese website!