package com.imed.costaccount.common.token; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; import com.imed.costaccount.common.exception.CostException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtil { @Value("${cost.jwt.secret}") private String secret; @Value("${cost.jwt.expire}") private Integer expire; public String createToken(Long userId) { Date date = DateUtil.offset(new DateTime(), DateField.DAY_OF_YEAR, expire).toJdkDate(); Algorithm algorithm = Algorithm.HMAC256(secret); String token = JWT.create().withClaim("userId", userId).withExpiresAt(date).sign(algorithm); return token; } public int getUserId(String token) { try { DecodedJWT decode = JWT.decode(token); Integer userId = decode.getClaim("userId").asInt(); return userId; } catch (JWTDecodeException e) { throw new CostException(500, "操作非法"); } } public void verifierToken(String token) { Algorithm algorithm = Algorithm.HMAC256(secret); JWT.require(algorithm).build().verify(token); } }