Spring Boot使用JWT進行token驗證

weixin_33850890發表於2018-08-30

JWT(JAVA WEB TOKEN) 就是用來生成token的。具體什麼原理優點作用百度一大把,這裡就不貼了

如何使用

1. 引入依賴

      <!-- JWT APP Token生成解決方案-->
      <dependency>
           <groupId>com.auth0</groupId>
           <artifactId>java-jwt</artifactId>
           <version>3.3.0</version>
       </dependency>

2. 建立工具類

package com.eliteai.et8080;

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 org.springframework.util.StringUtils;

import java.util.*;

/**
 * APP登入Token的生成和解析
 *
 */
public class JwtToken {

    /** token祕鑰,請勿洩露,請勿隨便修改 */
    public static final String SECRET = "poy7go/IVV7+rly0uJY9Vw==";
    /** token 過期時間: 60小時 */
    public static final int CALENDARFIELD = Calendar.HOUR;
    public static final int CALENDARINTERVAL = 60;

    /**
     * JWT生成Token.<br/>
     *
     * JWT構成: header, payload, signature
     *
     * @param userId
     *            登入成功後使用者userId, 引數userId不可傳空
     */
    public static String createToken(Long userId) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(CALENDARFIELD, CALENDARINTERVAL);
        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}
         *
         * withHeader : header
         * withClaim : payload
         * withIssuedAt : sign time
         * withExpiresAt : expire time
         * sign :signature
         */
        return JWT.create().withHeader(map)
                .withClaim("iss", "Service")
                .withClaim("aud", "APP")
                .withClaim("user_id", null == userId ? null : userId.toString())
                .withIssuedAt(iatDate)
                .withExpiresAt(expiresDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        Map<String, Claim> claims = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
            claims = jwt.getClaims();
            Optional.ofNullable(claims).orElseThrow(IllegalArgumentException::new);
        } catch (Exception e) {
            // e.printStackTrace();
            // token 校驗失敗, 丟擲Token驗證非法異常
            System.out.println("IllegalArgumentException : token 校驗失敗");
        }
        return claims;
    }

    /**
     * 根據Token獲取user_id
     *
     * @param token
     * @return user_id
     */
    public static Long getAppUID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim userIdClaim = claims.get("user_id");
        if (null == userIdClaim || StringUtils.isEmpty(userIdClaim.asString())) {
            // token 校驗失敗, 丟擲Token驗證非法異常
        }
        return Long.valueOf(userIdClaim.asString());
    }
    public static void main(String[] args){
        try {
            String token = createToken(1L);
            System.out.println("token ======== " + token);
            //Long appUID = getAppUID(token);
            //System.out.println("appUID ======== " + appUID);
            Map<String, Claim> claimMap = verifyToken(token);
            System.out.println("claimMap ======== " + claimMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 如何使用

請執行下main方法看看就知道怎麼使用了
謝謝觀賞!

相關文章