Jwt 生成與驗證

添加maven依賴java

<dependency>
       <groupId>io.jsonwebtoken</groupId>
       <artifactId>jjwt</artifactId>
       <version>0.9.0</version>
</dependency>

建立JwtManageweb

package com.antong.common.jwt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSON;
import com.antong.common.exception.AuthException;
import com.antong.common.util.Base64Kit;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

public class JwtManager {
	
	/**
	 * token有效期 (30 min)
	 */
	private static final long JWT_VALIDITYTIME = 1800000;
	
	/**
	 * token簽名
	 */
	private static final String JWT_SECRET = "jwtjwtjwtjwtjwtjwtjwt";
	
	private static final JwtManager me = new JwtManager();
	
	public static JwtManager me() {
		return me;
	}
	
	private JwtManager() {}

    public Map verifyJwtToken(String token) {
        SecretKey secretKey = generalKey();
        try {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            String subject = claims.getSubject();

            if (subject == null || subject.trim().length() == 0) {
                return null;
            }

            return JSON.parseObject(subject, HashMap.class);

        } catch (SignatureException | MalformedJwtException e) {
            // don't trust the JWT!
            // jwt 簽名錯誤或解析錯誤,多是僞造的,不能相信
        	throw new AuthException("401", "jwt token 簽名錯誤或解析錯誤。");
        } catch (ExpiredJwtException e) {
            // jwt 已通過期
        	throw new AuthException("401", "jwt token 已過時,請從新登陸。");
        }
    }

    public String createJwtToken(Map subjectMap) {

        String subject = JSON.toJSONString(subjectMap);
        SecretKey secretKey = generalKey();

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, secretKey);
        if (JWT_VALIDITYTIME > 0) {
            long expMillis = nowMillis + JWT_VALIDITYTIME;
            builder.setExpiration(new Date(expMillis));
        }
        return builder.compact();
    }
    
    /**
     * 經過未過時的token從新生成一個token
     * @param token  未過時token
     * @return 從新生成一個token
     */
    public String refreshJwtToken(String token){
    	Map subjectMap = verifyJwtToken(token);
    	String refreshToken = null;
    	if(subjectMap != null){
    		refreshToken = createJwtToken(subjectMap);
    	}
    	return refreshToken;
    }


    private SecretKey generalKey() {
        byte[] encodedKey = Base64Kit.decode(JWT_SECRET);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    public static void main(String[] args) {
    	Map<String, Object> subjectMap =  new HashMap<String, Object>();
    	subjectMap.put("username", "cyp");
    	subjectMap.put("password", "123456");
    	subjectMap.put("id", "j087aw6mSpqbTkneFoWbChO33n8=");
    	
    	
    	String token = JwtManager.me.createJwtToken(subjectMap);
    	System.out.println("createtoken:" + token);
    	Map<String, Object> sub = JwtManager.me.verifyJwtToken(token);
    	System.out.println(sub);
    	
    	/*String token = JwtManager.me().refreshJwtToken("eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjUzMzg3OTAsInN1YiI6IntcInVzZXJuYW1lXCI6XCJ0dW96cVwifSIsImV4cCI6MTUyNTMzODg1MH0.iEEOqUIFXCflD0mS7mXAxzhsTq4y0pscJU20-uz4jSQ");
    	Map<String, Object> sub = JwtManager.me.verifyJwtToken(token);
    	System.out.println(sub);*/
	}
}
相關文章
相關標籤/搜索