How to use jwt+security in spring-boot-3-jwt-security

Table of contents

In the SecurityApplication class

AuthenticationService

register method

authenticate method

saveUserToken略

revokeAllUserTokens method

refreshToken method

ApplicationConfig

Bean:UserDetailsService

Bean:AuthenticationProvider

Bean:AuthenticationManager

Bean:PasswordEncoder

JwtAuthenticationFilter

JwtService

LogoutService

SecurityConfiguration

other


This article is about spring-boot-3-jwt-security currently 800star

Pre-reading operation: download the project and take a look for yourself

environment:

jdk17

Maven 3+

pgsql

Spring Boot 3.0

Spring Security

JWT(JSON Web Tokens)

Lombok

Corresponding colors are buried pits and corresponding solutions

In the SecurityApplication class

It is the same as the startup class we wrote, with an additional CommandLineRunner bean.

The AuthenticationService in this bean , let's skip the bottom and observe again. It is obvious that two users are built and the user is "registered" to the AuthenticationService .

As for the bean of this CommandLineRunner

It is an interface for executing specific code when the application starts. When the application startup is complete, Spring Boot will automatically run CommandLineRunnerthe Bean that implements the interface.

CommandLineRunnerThe main function of the interface is to perform some initialization or preprocessing tasks when the application starts. You can place the code that needs to be run at application startup in CommandLineRunnera class that implements the interface and register it as a Spring Bean via annotation or configuration.

 Next, let's see how the register of AuthenticationService is implemented

AuthenticationService

Looking around, it is a service class related to certification standards. We analyze methods one by one.

register method

Parameters: It receives a class RegisterRequest with user attribute.

step:

1. Construct a user according to the parameters, where the password is encrypted with passwordEncoder

2. Put the built user into the library

3. Generate a token for this constructed user

4. Generate RefreshToken for this built user

5. Put the token into the warehouse. Note: token is associated with userId

6. return

authenticate method

Parameters: email and password (similar to logging in with email and password, and can also be compared to login with username and password)

step:

1. Check the email password according to the input parameters

2. Generate a token for this user

3. Generate RefreshToken for this user

4. Let the tokens under the user expire

5. Put the newly generated token into the warehouse

6. return

saveUserToken略

revokeAllUserTokens method

Parameters: user

step:

1. Find all the tokens of this user

2. Set the expiration field of all tokens to true

3. Update token

refreshToken method

Parameters: HttpServletRequest and HttpServletResponse

step:

1. Obtain the requested RefreshToken

2. Obtain user mailbox through RefreshToken

3. Find the user from the library

4. Verify that the user and the RefreshToken are valid

5. Generate a token for the user , cancel all tokens in the user library , and store them in the token library

6. Return

Having said that, the process is probably clear, let us focus on more details

ApplicationConfig

Bean:UserDetailsService

Implemented the loadUserByUsername method of the UserDetailsService interface

Check the user corresponding to the mailbox sent from the database

Bean:AuthenticationProvider

Configure the Provider, and call the implementation of UserDetailsService in the source code to verify during authentication

Bean:AuthenticationManager

The default is ProviderManager

Bean:PasswordEncoder

Use BCryptPasswordEncoder

JwtAuthenticationFilter

Inheriting OncePerRequestFilter is a filter base class provided by Spring Security to ensure that each request is only filtered once.

Implementation steps of doFilterInternal

1. If it is an authentication interface, it will be released

2. If there is no Authorization header or no token, it will be allowed

3. Find the user mailbox according to the token

4. Find the user from the database

5. Check whether the token is available

6. Verify the validity of token and user

7. Set the authentication object to the security context of the current thread

8. Release

JwtService

Read the key, token validity period and refreshToken validity period from the configuration file

There is nothing to say, mainly use tools to build tokens, get user names and other functional encapsulations based on tokens

LogoutService

The LogoutHandler is implemented mainly to process the logout operation, such as the database token setting expires, and the security thread context is cleared.

SecurityConfiguration

Annotate the function of EnableWebSecurity as shown in the figure below

 Annotate the function of EnableMethodSecurity as shown in the figure below

 The bean of SecurityFilterChain is configured with restrictions on http requests. This is a general configuration class. You will find that some of the beans we parsed above will appear here, such as JwtAuthenticationFilter and LogoutHandler.

In this bean, you can customize the configuration of your own interface, and the semantic function of the method is relatively clear, so I will not explain the methods one by one.

other

The above explanation is mainly from the service layer and details. Below you can find out how to use annotations to control permissions from AdminController.

Generally speaking, the project is relatively simple, but it is enough for you to understand jwt and security, and it can be regarded as ready-to-use scaffolding.

Guess you like

Origin blog.csdn.net/wai_58934/article/details/131640286