An article takes you to get Spring Security combined with Jwt to achieve stateless login

There are many login strategies in front-end and back-end separation projects, but JWT is currently a popular solution. This article will share with you how to use Spring Security and JWT together to achieve front-end and back-end separation. Time's login solution.

1. Stateless login

1. What is statefulness?

Stateful service, that is, the server needs to record the client information of each session, so as to identify the client's identity, and process the request according to the user's identity. A typical design is the Session in Tomcat

For example, login: After the user logs in, we save the user's information in the server session, and give the user a cookie value, record the corresponding session, and then the next request, the user carries the cookie value (this step is automatically completed by the browser) , We can identify the corresponding session to find the user's information.
This method is currently the most convenient, but it also has some drawbacks, as follows:

(1) The server saves a large amount of data, which increases the pressure on the server
(2) The server saves the user state and does not support clustered deployment

2. What is stateless?

Each service in the microservice cluster uses a RESTful style interface for external provision.
And one of the most important specifications of the RESTful style is the statelessness of services, namely:

The server does not store any client requester information
. Each client request must have self-descriptive information, and the client's identity can be identified through this information

So what are the benefits of this statelessness?

Client requests do not rely on server information, and multiple requests do not need to access the same server
. The cluster and state of the server are transparent to the
client. The server can be migrated and scaled arbitrarily (cluster deployment is convenient) to
reduce the server Storage pressure

3. How to achieve statelessness?

The process of stateless login:

First, the client sends the account name/password to the server for authentication. After the
authentication is passed, the server encrypts and encodes the user information into a token, which is returned to the client.
After the client sends a request, it needs to carry the authentication token
server pair. The token sent by the client is decrypted, judged whether it is valid, and the user login information is obtained

二、JWT

1. Introduction to JWT

JWT, the full name is Json Web Token, is a JSON-style lightweight authorization and identity authentication specification that can realize stateless, distributed Web application authorization:

Insert picture description here
As a specification, JWT is not tied to a certain language. The commonly used Java implementation is the open source project jjwt on GitHub. The address is as follows:https://github.com/jwtk/jjwt

2. JWT data format

JWT contains three parts of data:

  1. Header: Header, usually the header has two parts of information:

Declaration type, here is JWT
encryption algorithm, custom

We will Base64Url encoding (decodable) on the header to get the first part of the data.

  1. Payload: The payload is valid data. In the official document (RFC7519), here are 7 sample information:

iss (issuer): the issuer
exp (expiration time): the token expiration time
sub (subject): subject
aud (audience): audience
nbf (Not Before): effective time
iat (Issued At): issuance time
jti (JWT ID ):Numbering

This part will also use Base64Url encoding to get the second part of the data.

  1. Signature: The signature is the authentication information of the entire data. Generally, based on the data of the first two steps, plus the secret key of the service (the secret key is stored on the server and cannot be leaked to the client), it is generated by the encryption algorithm configured in the Header. Used to verify the integrity and reliability of the entire data.
    The generated data format is as follows:

Insert picture description here
Note that, where the data through .spaced into three portions, respectively corresponding to the aforementioned three parts, in addition, where data are not wrap, wrap pictures show only for convenience only.

3. JWT interaction process

Flow chart:
Insert picture description here
step translation:

The application or client requests authorization from the authorization server. After the authorization is
obtained, the authorization server returns an access token to the
application. The application uses the access token to access protected resources (such as API)

Because the token issued by JWT already contains the user's identity information, and it will be carried in every request, so the service does not need to save user information, or even query the database, which conforms to the RESTful stateless specification.

4. Problems with JWT

Having said that, JWT is not seamless. Some problems caused by the client's maintenance of the login status still exist here. Examples are as follows:

(1) Renewal problem, this is one of the problems criticized by many people. The traditional cookie+session solution naturally supports renewal, but since the server does not save user status, it is difficult to solve the renewal problem perfectly. If redis is introduced , Although it can solve the problem, but jwt has become nondescript.
(2) Logout problem. Since the server no longer saves user information, it is generally possible to log out by modifying the secret. After the server secret is modified, the unexpired tokens that have been issued will fail authentication, and then log out, but after all, there is no The traditional logout is convenient.
(3) The password is reset. After the password is reset, the original token can still access the system. At this time, the secret needs to be forcibly modified.
(4) Based on the second and third points, it is generally recommended that different users use different secrets.

Three, actual SpringBoot integration JWT

(1) Add dependency:

Insert picture description here
Then add jwt dependency:

		<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

Needs to be added

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108578893