JWT generation and verification (2017-12-26 modified version)

Previous version: http://blog.csdn.net/h996666/article/details/78207031

Don't say it, just paste the code

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 issuance
 *
 */
public class JWT {

	// key key
	private static final String SECRET_KEY = "xxxxxxx";
	
	/**
	 * Construct the key
	 *
	 * @return
	 */
	private static SecretKey generalKey() {
		byte[] encodeKey = Base64.decode(SECRET_KEY);
		return new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
	}
	
	/**
	 * Issue JWT
	 *
	 * @param jti The unique identity of JWT, mainly used as a one-time token (allowing to be empty)
	 * @param sub JWT to which user (empty allowed)
	 * @param expiredTimeAt expiration time (current time ms + expired time ms), unit ms (allow to be empty)
	 * @param claims payload information
	 * @return
	 */
	public static String createJWT(String jti, String sub, long expiredTimeAt, Map<String, Object> claims) {
		// get the key
		SecretKey secretKey = generalKey();
		// Build the JWT, and set the issuance time and signature algorithm
		JwtBuilder builder = Jwts.builder()
				.setIssuedAt (new Date ())
				.signWith(SignatureAlgorithm.HS256, secretKey);
		// check jti
		if (! StringUtils.isBlank (jti)) {
			builder.setId (jti);
		}
		// check sub
		if(!StringUtils.isBlank(sub)) {
			builder.setSubject(sub);
		}
		// Expiration
		if (expiredTimeAt > 0) {
			Date expDate = new Date(expiredTimeAt);
			builder.setExpiration(expDate);
		}
		// check
		if (claims != null) {
			// save related information
			for (Map.Entry<String, Object> en : claims.entrySet()) {
				builder.claim(en.getKey(), en.getValue());
			}
		}
		return builder.compact();
	}
	
	/**
	 *
	 * Parse the JWT string
	 *
	 * @param jwt
	 * @return claims, including announcement claims, custom claims
	 * @throws ExpiredJwtException, SignatureException, Exception token has expired, signature verification failed, other errors
	 */
	public static Map<String, Object> parseJWT(String jwt) {
		SecretKey secretKey = generalKey();
		try {
			Map<String, Object> claims = Jwts.parser()
					.setSigningKey(secretKey)
					.parseClaimsJws(jwt)
					.getBody();
			return claims;
		} catch (Exception e) {
			e.printStackTrace ();
			return null;
		}
	}
	
	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", 10000);
		String jwt = createJWT("", "", System.currentTimeMillis() + 30*60*1000, map);
		System.out.println(jwt);
		
		/**
		 * Previously, parseJWT(jwt) returned the Claims object,
		 * Claims implements the Map interface, which is actually the encapsulation of the Map, so it can directly return the Map
		 */
		Map<String, Object> claims = parseJWT(jwt);
		System.out.println(claims.get("userId"));
		System.out.println(claims.get("iat"));
		System.out.println(claims.get("exp"));
	}

}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325734495&siteId=291194637