The practice of jwt (json web token) for spring security verification

In terms of system development, security verification is always the most important. From the most primitive session and cookie verification methods, to conforming to the restful style, meeting the requirements of front-end and back-end separation, and enabling https requests, all aspects are constantly changing. This article takes the practice of jwt (json web token) as an example to introduce one or two.

First, let's take a look at the concept of jwt. The flow chart is as follows:

flow chart

When the user initiates a login request, the server creates an encrypted jwt information as the token return value. In subsequent requests, the jwt information is used as the request header. After the server decrypts correctly, the stored user information can be obtained, indicating that the verification is passed; the decryption failure description The token is invalid or expired.

The encrypted jwt information is shown below, which is composed of three parts. They are Header, Payload, and Signature.

eyjhbgcioijiuzi1nij9.eyjqdgkioijqd3qilcjpyxqioje0nzynzyntesinn1yii6intcinvzzxjjzfwiojesxcjyb2xlswrcijoxfsisimv4cci6mtq3mtmxotq1mx0.vw-ppsl5bu4dmorma7uzpjbr0f6sqg3n3hquuky8j35o
1
2
Header contains two parts of information, alg refers to the encryption type, optional values ​​are HS256, RSA, etc., typ=JWT is a fixed value, indicating the type of token.

{
    "alg": "HS256",
    "typ": "JWT"
}
1
2
3
4
5
Payload refers to the signature information and content, generally including iss (issuer), exp (expiration time), sub (user information), aud (receiver), and other information. For details, please refer to the official website.

{
    "sub": "1234567890",
    "name": "John Doe",
    "admin": true
}
1
2
3
4
5
6
Signature is the signature for Header and Payload.

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
1
2
On the jwt official website, you can see that there are implementation versions in different languages. Here, the java version of jjwt is used. Not much to say, just look at the code directly, encryption and decryption are very simple:

/**
  * create jwt
  * @param id
  * @param subject
  * @param ttlMillis
  * @return
  * @throws Exception
  */
  public String createJWT(String id, String subject, long ttlMillis) throws Exception {
       SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 ;
       long nowMillis = System. currentTimeMillis();
       Date now = new Date( nowMillis);
       SecretKey key = generalKey();
       JwtBuilder builder = Jwts. builder()
            .setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
           .signWith(signatureAlgorithm, key);
       if (ttlMillis >= 0){
           long expMillis = nowMillis + ttlMillis;
           Date exp = new Date( expMillis);
           builder.setExpiration( exp);
       }
       return builder.compact();
 }

  /**
  * decrypt jwt
  * @param jwt
  * @return
  * @throws Exception
  */
  public Claims parseJWT(String jwt) throws Exception{
       SecretKey key = generalKey();
       Claims claims = Jwts. parser()
          .setSigningKey( key)
          .parseClaimsJws( jwt).getBody();
       return claims;
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
The encryption and decryption keys are generated by converting fixed strings; subject is the json string of user information; ttlMillis refers to the validity period of the token, which is short and needs to be updated regularly.

The token refresh method to be introduced here is to generate a refreshToken with a longer validity period while generating the token, and then the client periodically obtains the latest token according to the refreshToken. A sse (server send event) request is established between the browser and the server to achieve refresh. About sse has been introduced in the previous blog post, and I will not mention it here.

The complete source code of this article is stored on github, address: https://github.com/ahmu/spring-authorization-demo.

References:

1.jwt official website: https://jwt.io/

2.jjwt project: https://github.com/jwtk/jjwt

3.Introduction to JSON Web Tokens:https://jwt.io/introduction/

4.How to Create and verify JWTs in Java: https://stormpath.com/blog/jwt-java-create-verify

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326618787&siteId=291194637