Spring Boot integrate JWT

1. What JWT that?

JWT is an open standard, which defines a method for brevity, the method of the object as JSON safe to transfer information between both self-contained for communication. JWT can use the HMAC algorithm is RSA public key or keys to be signed.

Simply put, by generating a certain standard token, token may then be decrypted by the decryption algorithm inverse, so that the user can obtain information.

advantage:

1) Production token can contain basic information, such as id, user nicknames, avatars and other information, check the library again to avoid

2) stored on the client, the server does not take up memory resources

Disadvantages:

After token is base64 encoded, can be decoded, so the object token before encryption should not contain sensitive information, such as user permissions, passwords, etc.

2, JWT format: the header, load, signature

header+payload+signature

Head: mainly describes Signature Algorithm

Load: describes the encrypted object information, such as user id, etc., you can also add some stuff inside specifications, such as iss issuer, expiration time exp, Sub-oriented user

Signature: The main part is the first two encryption, to prevent the others to get the token be decrypted tampering token base

3, stored on the client jwt

You may be stored in a Cookie, localStorage inside and sessionStorage

4, related to the introduction and development dependent tools JWT

1) introducing dependent

<!-- JWT相关 -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.7.0</version>
</dependency>

2) development and production of token method

3) development of test methods token

Package com.haitaiinc.clinicpathservice.utils; 

Import com.haitaiinc.clinicpathservice.entity.UserInfo;
 Import io.jsonwebtoken.Claims;
 Import io.jsonwebtoken.Jwts;
 Import io.jsonwebtoken.SignatureAlgorithm;
 Import org.springframework.util.StringUtils; 

Import java.util.Date; 

public  class JwtUtils {
     public  static  Final String SUBJECT = "ADMIN" ; 

    / ** 
     * expiration time, in milliseconds, one week 
     * / 
    public  static  Final  Long the eXPIRE = 1000 * 60 * 60 * 24 *. 7 ; 

    / **
     * 秘钥
     */
    public static final String APPSECRET = "haitaiinc";

    /**
     * 生成jwt
     *
     * @param userInfo
     * @return
     */
    public static String geneJsonWebToken(UserInfo userInfo) {

        if (userInfo == null || StringUtils.isEmpty(userInfo.getUserId()) || StringUtils.isEmpty(userInfo.getUserName())) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", userInfo.getUserId())
                .claim("name", userInfo.getUserName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
            return claims;

        } catch (Exception e) {
        }
        return null;
    }
}

4) Test

package com.haitaiinc.clinicpathservice;

import com.haitaiinc.clinicpathservice.entity.UserInfo;
import com.haitaiinc.clinicpathservice.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.junit.jupiter.api.Test;

public class CommonTest {

    @Test
    public void testGeneJwt() {
        UserInfo user = new UserInfo();
        user.setUserId("admin");
        user.setUserName("管理员");

        String token = JwtUtils.geneJsonWebToken(user);
        System.out.println(token);

    }


    @Test
    public void testCheck() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlkIjoiYWRtaW4iLCJuYW1lIjoi566h55CG5ZGYIiwiaWF0IjoxNTc3NTU3MDU1LCJleHAiOjE1NzgxNjE4NTV9.VrrKtCTnxVN76JhpyIusCGq9Wj89wLor0OqIJ6s0zXo";
        Claims claims = JwtUtils.checkJWT(token);
        if (claims != null) {
            String id = (String) claims.get("id");
            String name = (String) claims.get("name");
            System.out.println(id);
            System.out.println(name);
        } else {
            System.out.println("非法token");
        }
    }
}

Guess you like

Origin www.cnblogs.com/jwen1994/p/12113888.html