SpringBootSecurity learning (13) separating front and rear ends of the plate JWT

JWT use

In front of a brief introduction to the default login page changed before and after the end of the separation method asynchronous interface login, you can help us achieve the basic front and rear ends of the separation login. But this basic login and front page there is a sign in the same place, is the use of session and cookie to maintain login state, problem with this approach is that the poor scalability. Stand-alone course, no problem, if it is a cluster of servers, or cross-domain service-oriented architecture, it requires data sharing session, each server can read the session.

One solution is persistent session data, or other written redis persistence layer. Various services receipt of the request, all requested data to the persistence layer. The advantage of this approach is obvious structure, the disadvantage is larger than engineering. Further, in case of hanging persistence, will single point of failure.

Another option is simply the server does not save session data, and all data is stored in the client, each request back to the server. JWT is a representative of this program. About JWT theoretical knowledge, it is recommended reference Ruan Yifeng Great God wrote the tutorial: JSON Web Token introductory tutorial , which I think is most likely to be written in a clear, jwt achieve the following is based on this tutorial to achieve.

Specific theoretical knowledge can refer to the tutorial, here simply under the process, after the user logs in successfully, returns a token in the header of the user information, the information which contains the encrypted user information and digital signature, the most important is the expiration time, customers after receiving end, are each access interface header with after this token, server authentication is successful representation logged in, expired before the new acquisition can be.

The token contains the specific content header (encryption information), carrier (user information), signature (signature two front portions) three large, with periods between the three blocks (i.e., ".") Connected together, form a complete token information

Process Design

According to previous theoretical knowledge, we have to design how to use jwt. First, we use jwt, you can no longer use the session and cookie, so the first step is:

  1. Configuring session in the security profile stateless.

Then consider building jwt message body, there are three parts, the first part is a header, content encryption type is:

file

Above code, alg property represents the signature algorithm (algorithm), default HMAC SHA256 (written HS256); typ attribute indicates the token (token) type (type), JWT token unified written as JWT, finally, the above JSON object Base64URL algorithm translated into strings using, as the first part. So the second step is:

  1. Configuring session in the security profile stateless.
  2. Determine the header information format

The next step to determine a second portion, message carrier (Payload), which is a json object used to store the actual data transfer is required. JWT provides for seven official field for the selection:

file

Of course, in addition to these may also add other content, such as user information, the algorithm Base64URL JSON objects are also used to turn the string, the third step and the fourth step is:

  1. Configuring session in the security profile stateless.
  2. Determine the header information format
  3. Determining the message body
  4. HMAC SHA256 algorithm using the message header and the signature as a third body part

Now token basically a combination of the message is complete, the user is logged and client access interfaces, should be placed header inside the token, the name of Authorization. So the final step is, client access non-normal login interfaces, verify the legitimacy token, so the overall design process is as follows:

  1. Configuring session in the security profile stateless.
  2. Determine the header information format
  3. Determining the message body
  4. HMAC SHA256 algorithm using the message header and the signature as a third body part
  5. Add filters, verify the legitimacy of token

Modify the configuration class

The above process design finished, we modify the project in accordance with the following procedure, first modify the security configuration class:

file

After configuration, start the project, access login, the login is successful you can see, not preserved any cookie.

JWT defined tools

First, let's define a few constants:

file

Base64URL algorithm then defines encoding and decoding methods:

file

Then define HmacSHA256 encryption algorithm and obtain the signature of the method:

file

The last method to design a simple authentication token is:

file

Such jwt tools to design well, these methods currently operating token enough content.

JWT message object definitions

Let's define the content jwt, in fact, very simple, three-part, therefore, can be defined in three fields:

file

Look at the constructor,

file

This construction method is very convenient to use it later to create objects, the three parts of jwt basically completed, header section and payload section are encoded signature also completed, so the following token can be generated directly rewrite toString method:

file

As can be seen from here, token overall default are not encrypted, but also can be encrypted. After generating the original Token, it can be re-encrypted with a key once. So do not put passwords and other important information into a token.

Modify the login is successful processor

After the user logs in successfully, the session will not be distributed to users, but to send to the user jwt, and therefore modify the login is successful processor as follows:

file

Note Manual above the user's password information is set to null. For convenience, a combination of objects directly fastjson.

Modifying entity class

With token when accessing interface, you need to log in token back to the user object, and therefore the same field name of our entity classes and token users in the band to change it, look at the role of entity classes:

file

Look at the user entity classes:

file

We can see, the basic principle is the need to amend the field name and the name of the parent class of the same line, which is the recommended field names.

Write token validation filter

After we changed the security of stateless session, although no longer transfer session, but the security filter did not fail, so the effect is caused by a successful login, access interface displays logged in. Now we will use the token before logging plus a token validation filter, and after the verification information directly into the SecurityContextHolder. Such verification token each time you log on to determine whether the login is no longer rely session. Look at this filter:

file

This filter is very simple, GenericFilterBean inherited class, direct access token, token is determined not empty, authentication token, and the token is removed from the user information payload, into the SecurityContextHolder, token validation fails or expired token directly returns an error. The logic is simple.

Finally, security class, this filter is arranged to the front:

file

So our custom jwt process is complete. Can test the postman, the first is the login:

file

After logging in, you can view the information in the header stood token, and then use the token header into another interface to access interface, you can see a successful visit:

file

Interested parties can debug trace it processes.

JWT several features

  • (1) JWT default is not encrypted, but also can be encrypted. After generating the original Token, it can be re-encrypted with a key once.

  • (2) in the case JWT without encryption, secret data can not be written JWT.

  • (3) JWT not only can be used for authentication, it can also be used to exchange information. Effective use of JWT, the number of server queries the database can be reduced.

  • (4) JWT biggest drawback is that, because the server does not save session state, a token can not be abolished in the course of, or change the permissions of the token. That is, once issued JWT, will remain in effect until maturity, unless the server to deploy additional logic.

  • (5) JWT itself contains authentication information, when disclosed, anyone can get all the permissions of the token. To reduce theft, JWT's validity should be set relatively short. For some of the more important rights, should once again to authenticate the user during use.

  • (6) In order to reduce fraud, the JWT codes using the HTTP protocol should not be transmitted, to use the HTTPS protocol.

Code Address: https://gitee.com/blueses/spring-boot-security 14

Guess you like

Origin www.cnblogs.com/guos/p/11622273.html