package cn.seecoder.seecoderbokserver.util; import cn.seecoder.seecoderbokserver.exception.MyServiceException; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @author mars */ @Component public class JwtUtil { private static String jwtSecret; @Value("${jwt.secret}") public void setJwtSecret(String jwtSecret) { //通过set让static方法读取配置文件中的值 JwtUtil.jwtSecret = jwtSecret; } public static String getJwtSecret() { return JwtUtil.jwtSecret; } public static Claim parseJwt(String token) { // jwtSecret JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build(); DecodedJWT decodedjwt; try { decodedjwt = jwtVerifier.verify(token); } catch (TokenExpiredException e) { throw new MyServiceException("A0230", "用户登陆已过期"); } catch (JWTVerificationException | IllegalArgumentException e) { //解析错误 或者 token写错 e.printStackTrace(); throw new MyServiceException("A0200", "登陆失败"); } // if (decodedjwt.getClaim("exp").asDate().before(new Date())) { // throw new MyServiceException("A0230", "用户登陆已过期"); // } return decodedjwt.getClaim("user_info"); } }