使用 JWT 生成 Token 代碼示例

JSON Web Token,簡稱 JWT, 是一個開放的標準(RFC 7519),它定義了以一種緊湊的、自包含的 JSON 對象在各方之間安全傳輸信息的方式。該信息含有數字簽名,能夠被驗證和信任。html

JWT的介紹這裏就不說了,想了解的能夠看一下這邊博客:JSON Web Token 入門教程java

或者直接參考官方網站:https://jwt.ioweb

項目是SpringBoot2.0,下面直接上代碼。json

Maven配置:安全

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

JWT工具:工具

這裏使用了自定義字段和官方建議字段測試

package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @date 2019/4/25 11:46
 * @atuther wangbo
 */
public class JwtUtil {

    //密鑰
    public static final String SECRET = "sdjhakdhajdklsl;o653632";
    //過時時間:秒
    public static final int EXPIRE = 5;

    /**
     * 生成Token
     * @param userId
     * @param userName
     * @return
     * @throws Exception
     */
    public static String createToken(String userId, String userName) throws Exception {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, EXPIRE);
        Date expireDate = nowTime.getTime();

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

        String token = JWT.create()
                .withHeader(map)//
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withSubject("測試")//
                .withIssuedAt(new Date())//簽名時間
                .withExpiresAt(expireDate)//過時時間
                .sign(Algorithm.HMAC256(SECRET));//簽名
        return token;
    }

    /**
     * 驗證Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token)throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("憑證已過時,請從新登陸");
        }
        return jwt.getClaims();
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Map<String, Claim> parseToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaims();
    }

}

測試類:網站

    public static void main(String[] args){
        try {
            String token = JwtUtil.createToken("12345", "wangbo");
            System.out.println("token=" + token);
            //Thread.sleep(5000);
            Map<String, Claim> map = JwtUtil.verifyToken(token);
            //Map<String, Claim> map = JwtUtil.parseToken(token);
            //遍歷
            for (Map.Entry<String, Claim> entry : map.entrySet()){
                if (entry.getValue().asString() != null){
                    System.out.println(entry.getKey() + "===" + entry.getValue().asString());
                }else {
                    System.out.println(entry.getKey() + "===" + entry.getValue().asDate());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

測試結果:ui

token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiLmtYvor5UiLCJ1c2VyTmFtZSI6IndhbmdibyIsImV4cCI6MTU1NjE3NjYwNiwidXNlcklkIjoiMTIzNDUiLCJpYXQiOjE1NTYxNzY2MDF9.FNVh-NbFHgScsbbuwLvQL-sOqLuaAoI8jxMvudq81J8
sub===測試
userName===wangbo
exp===Thu Apr 25 15:16:46 CST 2019
userId===12345
iat===Thu Apr 25 15:16:41 CST 2019

基本就是這些了。spa

相關文章
相關標籤/搜索