JWT实现单点登录

import com.hb.util.enums.ResponseCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import java.io.IOException;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

public class JwtUtil {
    public JwtUtil() {
    }

    public static String createJWT(String id, String subject, long ttl) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMS = System.currentTimeMillis();
        Date nowDate = new Date(nowMS);
        SecretKey key = generateKey();
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(nowDate).setSubject(subject).signWith(signatureAlgorithm, key);
        if (ttl >= 0L) {
            long expireMS = nowMS + ttl;
            Date expireDate = new Date(expireMS);
            builder.setExpiration(expireDate);
        }

        return builder.compact();
    }

    public static String createJWTWith30Day(String id, String subject) {
        return createJWT(id, subject, setTTL());
    }

    private static Long setTTL() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(2, 1);
        calendar.set(11, 2);
        calendar.set(12, 0);
        calendar.set(13, 0);
        return calendar.getTime().getTime() - System.currentTimeMillis();
    }

    private static Claims parseJWT(String jwt) throws SignatureException {
        SecretKey key = generateKey();
        return (Claims)Jwts.parser().setSigningKey(key).parseClaimsJws(removePrefix(jwt)).getBody();
    }

    private static SecretKey generateKey() {
        String stringKey = "7786df7fc3a34e26a61c034d5ec8245d";
        byte[] encodedKey = Base64.getDecoder().decode(stringKey);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

}

你可能感兴趣的:(工具类,java)