jjwt使用说明-笔记

jjwt官网链接:https://github.com/jwtk/jjwt

POM 依赖

<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-api</artifactId>
  <version>0.12.3</version>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-impl</artifactId>
  <version>0.12.3</version>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
  <version>0.12.3</version>
  <scope>runtime</scope>
</dependency>
<!-- Uncomment this next dependency if you are using:
- JDK 10 or earlier, and you want to use RSASSA-PSS (PS256, PS384, PS512) signature algorithms.  
- JDK 10 or earlier, and you want to use EdECDH (X25519 or X448) Elliptic Curve Diffie-Hellman encryption.
- JDK 14 or earlier, and you want to use EdDSA (Ed25519 or Ed448) Elliptic Curve signature algorithms.    
It is unnecessary for these algorithms on JDK 15 or later.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId> or bcprov-jdk15to18 on JDK 7
<version>1.76</version>
<scope>runtime</scope>
</dependency>
-->

生成token

PS: 基本和java-jwt使用一致。只是最新的jjwt舍弃了一些api,换了新的api

① 标准载荷:
JwtBuilder为JWT规范中定义的标准载荷提供了方便的构建器方法。
● issuer: sets the iss(Issuer) Claim jwt签发者
● subject: sets the sub(Subject) Claim jwt针对的用户
● audience: sets the aud(Audience) Claim 校验jwt的一方
● expiration: sets the exp(Expiration Time) Claim jwt过期时间
● notBefore: sets the nbf(Not Before) Claim 定义在某个时间前该jwt是不可用的
● issuedAt: sets the iat(Issued At) Claim 签发时间
● id: sets the jti(JWT ID) Claim jwt的唯一身份标识,作一次性token,防重放攻击。
② 自定义载荷:
● claime(key,value)
● claime(Map对象)

// 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法
private static SecretKey key = Jwts.SIG.HS256.key().build();

/**
 * 生成token
 * @return
 */
public static String genToken(){
    
    
    // 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jws
    String jws =  Jwts.builder().
            subject("Joe").  // setSubject 设置jwt针对的用户
            issuer("张三").   // issuer 签发人
            claim("name","zhangsan"). // 自定义载荷数据
            claim("role","admin"). // 自定义载荷数据
            signWith(key).   // token加签认证
            expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2H
            compact();  // 生成token字符串
    return jws;
}

生成token的两句核心代码:

SecretKey key = Jwts.SIG.HS256.key().build();
Jwts.builder().setSubject("Joe").signWith(key).compact();

验证解析token

 /**
 * token 校验
 * @param key  密钥
 * @param token jws
 * @return
 */
public static String checkToken(SecretKey key,String token ){
    
    
    String msg = null;
    try {
    
    
        Jws<Claims> claimsJws = Jwts.parser().
                verifyWith(key).
                build().
                parseSignedClaims(token);
        // 获取载荷的一些数据信息
        Claims payload = claimsJws.getPayload(); // payload 为一个map对象
        String issuer = payload.getIssuer();
        Date expiration = payload.getExpiration();
        String name = (String)payload.get("name");
        String role = (String)payload.get("role");
        // 测试就直接打印出去了...
        System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);
        return "token正确";
    } catch (SignatureException se) {
    
    
        msg = "密钥错误";
        return  msg;
    }catch (MalformedJwtException me) {
    
    
        msg = "密钥算法或者密钥转换错误";
        return  msg;
    }catch (MissingClaimException mce) {
    
    
        msg = "密钥缺少校验数据";
        return  msg;
    }catch (ExpiredJwtException mce) {
    
    
        msg = "密钥已过期";
        return  msg;
    }catch (JwtException jwte) {
    
    
        msg = "密钥解析错误";
        return  msg;
    }
}

完整代码

package jwt_test;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import javax.crypto.SecretKey;
import java.util.Date;

/**
 * jjwt
 */
public class JJwtUtils {
    
    

    // 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法
    private static SecretKey key = Jwts.SIG.HS256.key().build();

    /**
     * 生成token
     * @return
     */
    public static String genToken(){
    
    
        // 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jws
        String jws =  Jwts.builder().
                subject("Joe").  // setSubject 设置jwt针对的用户
                issuer("张三").   // issuer 签发人
                claim("name","zhangsan"). // 自定义载荷数据
                claim("role","admin"). // 自定义载荷数据
                signWith(key).   // token加签认证
                expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2H
                compact();  // 生成token字符串
        return jws;
    }

    /**
     * token 校验
     * @param key  密钥
     * @param token jws
     * @return
     */
    public static String checkToken(SecretKey key,String token ){
    
    
        String msg = null;
        try {
    
    
            Jws<Claims> claimsJws = Jwts.parser().
                    verifyWith(key).
                    build().
                    parseSignedClaims(token);
            // 获取载荷的一些数据信息
            Claims payload = claimsJws.getPayload(); // payload 为一个map对象
            String issuer = payload.getIssuer();
            Date expiration = payload.getExpiration();
            String name = (String)payload.get("name");
            String role = (String)payload.get("role");
            // 测试就直接打印出去了...
            System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);
            return "token正确";
        } catch (SignatureException se) {
    
    
            msg = "密钥错误";
            return  msg;
        }catch (MalformedJwtException me) {
    
    
            msg = "密钥算法或者密钥转换错误";
            return  msg;
        }catch (MissingClaimException mce) {
    
    
            msg = "密钥缺少校验数据";
            return  msg;
        }catch (ExpiredJwtException mce) {
    
    
            msg = "密钥已过期";
            return  msg;
        }catch (JwtException jwte) {
    
    
            msg = "密钥解析错误";
            return  msg;
        }
    }


    /**
    * 	测试
    */
    public static void main(String[] args) {
    
    
        String token = genToken();
        System.out.println(token);
        // 断言测试
        // assert Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload().getSubject().equals("Joe");
        String res = checkToken(key, token);
        System.out.println(res);
    }

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_63622279/article/details/134562409