JwtTokenUtil.java 4.2 KB
Newer Older
liqin's avatar
liqin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
package cn.wisenergy.chnmuseum.party.auth.util;

import cn.wisenergy.chnmuseum.party.common.util.DateUtil80;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

@Component
public class JwtTokenUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    private static String jwtTokenSecret;
    private static String jwtTokenIssuer;
    private static String jwtTokenExpiration;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.secret}")
    public void setJwtTokenSecret(String jwtTokenSecret) {
        JwtTokenUtil.jwtTokenSecret = jwtTokenSecret;
    }

    @Value("${jwt.issuer}")
    public void setJwtTokenIssuer(String jwtTokenIssuer) {
        JwtTokenUtil.jwtTokenIssuer = jwtTokenIssuer;
    }

    @Value("${jwt.expiration}")
    public void setJwtTokenExpiration(String jwtTokenExpiration) {
        JwtTokenUtil.jwtTokenExpiration = jwtTokenExpiration;
    }

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static String verify(String token, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(jwtTokenIssuer).withSubject(username).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("employee_id").asString();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getEmployeeId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("employee_id").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,60min后过期
     *
     * @param username 用户名
     * @return 加密的token
     */
    public static String sign(String username, String employeeId) throws UnsupportedEncodingException {
        LocalDateTime currentTime = DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis());
        Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
        // 附带username信息
        return JWT.create().withIssuer(jwtTokenIssuer)
                // 创建时间
                .withIssuedAt(DateUtil80.getCurrDateTime()).withSubject(username).withClaim("employee_id", employeeId)
                .withExpiresAt(DateUtil80.asDate(currentTime.plusMinutes(240))).sign(algorithm);
    }

    /**
     * 生成签名,30day后过期
     *
     * @param username 用户名
     * @return 加密的token
     */
    public static String signByRememberMe(String username, Integer userId) throws UnsupportedEncodingException {
        LocalDateTime currentTime = DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis());
        Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
        // 附带username信息
        return JWT.create().withIssuer(jwtTokenIssuer)
                // 创建时间
                .withIssuedAt(DateUtil80.getCurrDateTime()).withSubject(username).withClaim("userId", userId)
                .withExpiresAt(DateUtil80.asDate(currentTime.plusSeconds(Integer.parseInt(jwtTokenExpiration))))
                .sign(algorithm);
    }

}