久久久久久AV无码免费看大片,亚洲一区精品人人爽人人躁,国产成人片无码免费爱线观看,亚洲AV成人无码精品网站,为什么晚上搞的时候要盖被子

java中jwt的使用方法

時間:2024-01-16 09:40:54 類型:JAVA
字號:    

一. 引入JAR包

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.45</version>
</dependency>

二. 創(chuàng)建JWT工具類

public class JWTUtils {
    /** token秘鑰,請勿泄露 */
    public static final String SECRET = "#@$_&^#@DSWER#@";
    /**
     *
     * @param userName : 用戶名
     * @return  生成的字符串Token值
     */
    public static String createToken(String userName) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
//        nowTime.add(Calendar.SECOND, 1 * 24 * 60 * 60);
        nowTime.add(Calendar.SECOND, 1* 24 * 60 * 60); //一天過期
        //過期時間1天
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP")
                .withClaim("userName", null == userName ? null : userName)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature
        return token;
    }

    /**
     * 解密Token
     *
     * @param token: 服務器端生成的Token發(fā)送給客戶端,客戶端再傳遞過來需要驗證的Token
     * @return  返回驗證結(jié)果: code:{0:success, 1:fail}
     */
    public static Map<String,Object> verifyToken(String token) {
        Map<String, Claim> claims = null;
        Map<String,Object> map = new HashMap<>();
        map.put("code",1); //默認為驗證失敗 0: 驗證成功
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            claims = verifier.verify(token).getClaims();
            map.put("code",0);
            map.put("msg", "success");
        }
        catch (SignatureVerificationException e){
            map.put("msg","簽名無效");
        }
        catch (AlgorithmMismatchException e){
            map.put("msg","簽名算法不匹配");

        }
        catch (TokenExpiredException e){
            map.put("msg","token過期");
        }
        map.put("claims",claims);
        return map;
    }
}

二. 生成及驗證測試

public static void main(String[] args) {
         //生成Token, 登陸成功后,將生成的Token返回給客戶端
        String token = JWTUtils.createToken("xiaomi");
        //收到客戶端通過ajax傳遞過來的token,將驗證結(jié)果返回給用戶
        //客戶將根據(jù)這里返回的code,msg進行判斷驗證
        String json = JSON.toJSONString(JWTUtils.verifyToken(token));
        //使用阿里的fastjson2類
        System.out.println(json);
}


<