|
| 1 | +package top.cadecode.common.util; |
| 2 | + |
| 3 | +import com.nimbusds.jose.*; |
| 4 | +import com.nimbusds.jose.crypto.MACSigner; |
| 5 | +import com.nimbusds.jose.crypto.MACVerifier; |
| 6 | +import com.nimbusds.jwt.JWTClaimsSet; |
| 7 | +import com.nimbusds.jwt.SignedJWT; |
| 8 | +import lombok.Data; |
| 9 | +import lombok.SneakyThrows; |
| 10 | +import org.springframework.boot.context.properties.ConfigurationProperties; |
| 11 | +import org.springframework.stereotype.Component; |
| 12 | +import top.cadecode.common.core.exception.CommonException; |
| 13 | +import top.cadecode.common.enums.FrameErrorEnum; |
| 14 | + |
| 15 | +import java.util.Date; |
| 16 | +import java.util.List; |
| 17 | +import java.util.Map; |
| 18 | + |
| 19 | +/** |
| 20 | + * @author Cade Li |
| 21 | + * @date 2021/12/10 |
| 22 | + * @description Token 工具类 |
| 23 | + */ |
| 24 | +@Data |
| 25 | +@Component |
| 26 | +@ConfigurationProperties(prefix = "simple.jwt") |
| 27 | +public class TokenUtil { |
| 28 | + |
| 29 | + private String header; |
| 30 | + private String refreshHeader; |
| 31 | + private Long expiration; |
| 32 | + private Long refreshExpiration; |
| 33 | + private String secret; |
| 34 | + |
| 35 | + /** |
| 36 | + * 生成 token |
| 37 | + * |
| 38 | + * @param name 用户名 |
| 39 | + * @param roles 角色 |
| 40 | + * @return token 字符串 |
| 41 | + */ |
| 42 | + public String generateToken(String name, List<String> roles) { |
| 43 | + long expiredTime = new Date().getTime() + expiration * 1000; |
| 44 | + JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256); |
| 45 | + JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder() |
| 46 | + .claim("name", name). |
| 47 | + claim("roles", roles) |
| 48 | + .expirationTime(new Date(expiredTime)).build(); |
| 49 | + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet); |
| 50 | + try { |
| 51 | + signedJWT.sign(new MACSigner(secret)); |
| 52 | + return signedJWT.serialize(); |
| 53 | + } catch (JOSEException e) { |
| 54 | + throw CommonException.of(FrameErrorEnum.JWT_CREATE_ERROR).suppressed(e); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * 校验 token |
| 60 | + * |
| 61 | + * @param token token 字符串 |
| 62 | + * @return 是否通过校验 |
| 63 | + */ |
| 64 | + public Map<String, Object> verifyToken(String token) { |
| 65 | + try { |
| 66 | + JWSObject jwsObject = JWSObject.parse(token); |
| 67 | + JWSVerifier verifier = new MACVerifier(secret); |
| 68 | + boolean verify = jwsObject.verify(verifier); |
| 69 | + if (verify) { |
| 70 | + return jwsObject.getPayload().toJSONObject(); |
| 71 | + } |
| 72 | + return null; |
| 73 | + } catch (Exception e) { |
| 74 | + throw CommonException.of(FrameErrorEnum.JWT_VERIFY_ERROR).suppressed(e); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments