JWT 생 성 및 검증(2017-12-26 수정판)

2928 단어 자바 기반
이전 버 전:http://blog.csdn.net/h996666/article/details/78207031
말 하지 말고 코드 를 붙 여 라.
package com.life.app.token;

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

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

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Base64;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


/**
 * Json web token   
 *
 */
public class JWT {

	//   key
	private static final String SECRET_KEY = "xxxxxxx";
	
	/**
	 *     
	 * 
	 * @return
	 */
	private static SecretKey generalKey() {
		byte[] encodeKey = Base64.decode(SECRET_KEY);
		return new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
	}
	
	/**
	 *   JWT
	 * 
	 * @param jti JWT       ,         token(    )
	 * @param sub JWT      (    )
	 * @param expiredTimeAt     (    ms+     ms),  ms(    )
	 * @param claims     
	 * @return
	 */
	public static String createJWT(String jti, String sub, long expiredTimeAt, Map claims) {
		//     
		SecretKey secretKey = generalKey();
		//   JWT,       ,    
		JwtBuilder builder = Jwts.builder()
				.setIssuedAt(new Date())
				.signWith(SignatureAlgorithm.HS256, secretKey);
		//   jti
		if(!StringUtils.isBlank(jti)) {
			builder.setId(jti);
		}
		//   sub
		if(!StringUtils.isBlank(sub)) {
			builder.setSubject(sub);
		}
		//     
		if (expiredTimeAt > 0) {
			Date expDate = new Date(expiredTimeAt);
			builder.setExpiration(expDate);
		}
		//   
		if (claims != null) {
			//       
			for (Map.Entry en : claims.entrySet()) {
				builder.claim(en.getKey(), en.getValue());
			}
		}
		return builder.compact();
	}
	
	/**
	 * 
	 *   JWT   
	 * 
	 * @param jwt
	 * @return claims,      ,     
	 * @throws ExpiredJwtException,SignatureException,Exception token   ,      ,    
	 */
	public static Map parseJWT(String jwt) {
		SecretKey secretKey = generalKey();
		try {
			Map claims = Jwts.parser()
					.setSigningKey(secretKey)
					.parseClaimsJws(jwt)
					.getBody();
			return claims;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("userId", 10000);
		String jwt = createJWT("", "", System.currentTimeMillis() + 30*60*1000, map);
		System.out.println(jwt);
		
		/**
		 *   parseJWT(jwt)    Claims  ,
		 * Claims   Map  ,      Map     ,        Map
		 */
		Map claims = parseJWT(jwt);
		System.out.println(claims.get("userId"));
		System.out.println(claims.get("iat"));
		System.out.println(claims.get("exp"));
	}

}

좋은 웹페이지 즐겨찾기