Spring Security is a very powerful framework in the Spring family for authentication and permission control, and we can easily extend it to meet our current system security requirements.
This demo mainly uses Spring Security and Spring Boot, and all the dependencies adopt the latest stable version. Beyond the initial project, the JPA technology was also used.
Some frameworks/services used in the project:
- Database: H2 in-memory database, no manual installation required.
- Cache : Redis
- Permission framework: Spring Security
- ORM framework : JPA (a small amount of SQL)
- Interface documentation :
- swagger. online API documentation at http://localhost:8081/api/swagger-ui/ .
- The swagger functionality is currently enhanced using knife4j at http://localhost:8081/api/doc.html
- Add H2 in-memory database support, no need for MySQL, just one click to start the project to access http://localhost:8081/api/h2-console (username:root,password:root)
- Add Swagger, easy to call interface
- Refactor the exception handling part of the code to optimize the return structure
- Create a new role table, then associate users with roles by creating a new role_user table
- File structure refactoring
- add Jpa auditing functionality
- login (login) interface exposed at controller level
- Logout function: redis stores token information (key->user id,value->token) and removes the token information from redis after logout
- Re-login will update the token information stored in redis
- git clone this repo.
- open project and wait maven to install project Dependencies
- change
application.properties
change the database connection information parameter to your own - Run the project (related data tables will be created automatically, if you don't understand, take a look at JPA)
URL: POST http://localhost:8081/api/users/sign-up
RequestBody:
{"userName":"jake","fullName":"IronMan","password":"123"}
Newly registered users are bound by default to the following roles: USER and MANAGER.
URL:POST http://localhost:8081/api/auth/login
RequestBody:
{"username": "jake", "password": "123","rememberMe":true}
We use a GET request to access /api/users
, the access rights for this interface are:
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_MANAGER','ROLE_ADMIN')")
We use GET requests to access /api/users
but without a token or with an invalid token.
URL:POST http://localhost:8081/api/users?username=jake
We use a DELETE request to access /api/users?username=xxx
, carrying a valid token, but the token does not have enough access rights.