JWT的生成與驗(yàn)證及工具類(lèi)的封裝

引入依賴(lài)

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.4.0</version>
</dependency>

獲取token

void test1() {
        Map<String, Object> map = new HashMap<>();

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 2000);

        String token = JWT.create()
                .withHeader(map) //header,可以不需要有默認(rèn)的
                .withClaim("userId", 99)//payload,可以多個(gè)
                .withClaim("username", "xpt")//payload
                .withExpiresAt(instance.getTime())//指定令牌的過(guò)期時(shí)間
                .sign(Algorithm.HMAC256("jsh#@JSH.z")) //簽名
                ;
        System.out.println(token);
}

驗(yàn)證token

/**
     * 令牌驗(yàn)證:根據(jù)令牌和簽名解析數(shù)據(jù)
     * 常見(jiàn)異常:
     *     SignatureVerificationException 簽名不一致異常
     *     TokenExpiredException 令牌過(guò)期異常
     *     AlgorithmMismatchException 算法不匹配異常
     *     InvalidClaimException 失效的payload異常
     */
void test2() {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTg4MzQ5NjksInVzZXJJZCI6OTksInVzZXJuYW1lIjoieHB0In0.TWGVQZZP4t3iB2G3PIHIUt1NFWQ80LVBc1cYNWI42aM";
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("jsh#@JSH.z")).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        System.out.println("用戶(hù)Id:" + decodedJWT.getClaim("userId").asInt());
        System.out.println("用戶(hù)名:" + decodedJWT.getClaim("username"));
        System.out.println("過(guò)期時(shí)間:" + decodedJWT.getExpiresAt());
}

封裝成工具類(lèi)

public class JWTUtils {
    private static String TOKEN = "token!Q@W3e4r";
    /**
     * 生成token
     * @param map  //傳入payload
     * @return 返回token
     */
    public static String getToken(Map<String,Object> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,7);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN));
    }
    /**
     * 驗(yàn)證token
     * @param token
     * @return
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);  // 如果驗(yàn)證通過(guò),則不會(huì)把報(bào)錯(cuò),否則會(huì)報(bào)錯(cuò)
    }
    /**
     * 獲取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容