Jwt 生成与验证

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

添加maven依赖


       io.jsonwebtoken
       jjwt
       0.9.0

创建JwtManage

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 subjectMap =  new HashMap();
    	subjectMap.put("username", "cyp");
    	subjectMap.put("password", "123456");
    	subjectMap.put("id", "j087aw6mSpqbTkneFoWbChO33n8=");
    	
    	
    	String token = JwtManager.me.createJwtToken(subjectMap);
    	System.out.println("createtoken:" + token);
    	Map sub = JwtManager.me.verifyJwtToken(token);
    	System.out.println(sub);
    	
    	/*String token = JwtManager.me().refreshJwtToken("eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjUzMzg3OTAsInN1YiI6IntcInVzZXJuYW1lXCI6XCJ0dW96cVwifSIsImV4cCI6MTUyNTMzODg1MH0.iEEOqUIFXCflD0mS7mXAxzhsTq4y0pscJU20-uz4jSQ");
    	Map sub = JwtManager.me.verifyJwtToken(token);
    	System.out.println(sub);*/
	}
}

 

转载于:https://my.oschina.net/u/2276456/blog/1836252

你可能感兴趣的:(Jwt 生成与验证)