1.引入jwt依赖库
com.auth0 java-jwt 3.16.0
2.添加jwt配置属性:密钥、过期天数
emos: jwt: #密钥 secret: abc123456 #令牌过期时间(天) expire: 5 #令牌缓存时间(天数) cache-expire: 10
3.添加工具类,生成token、解析token、校验token有效性
import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.example.emos.wx.exception.EmosException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; @Component @Slf4j public class JwtUtil { // 密钥 @Value("${emos.jwt.secret}") private String secret; // 过期时间(天) @Value("${emos.jwt.expire}") private int expire; /** * 传入userId生成token * @param userId * @return */ public String createToken(int userId) { Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire).toJdkDate(); Algorithm algorithm = Algorithm.HMAC256(secret); // 创建加密算法对象 JWTCreator.Builder builder = JWT.create(); String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm); return token; } /** * 从token中解析出userId * @param token * @return */ public int getUserId(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("userId").asInt(); } catch (Exception e) { throw new EmosException("令牌无效"); } } /** * 校验token有效性 * @param token */ public void verifierToken(String token) { Algorithm algorithm = Algorithm.HMAC256(secret); // 创建加密算法对象 JWTVerifier verifier = JWT.require(algorithm).build(); verifier.verify(token); } }