package com.xjhs.findmemerchant.security; import org.jose4j.jws.AlgorithmIdentifiers; import org.jose4j.jws.JsonWebSignature; import org.jose4j.jwt.JwtClaims; import org.jose4j.jwt.NumericDate; import org.jose4j.jwt.consumer.JwtConsumer; import org.jose4j.jwt.consumer.JwtConsumerBuilder; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; @Component public class JwtTokenService { // 建议改成配置:application.yml 里 private final String secret = "secret-key-123456789012345678901234567890"; private final long expireMillis = 30 * 24 * 60 * 60 * 1000L; // 30 天 /** * 生成 JWT */ public String generateToken(String mobile) throws Exception { JwtClaims claims = new JwtClaims(); claims.setSubject(mobile); claims.setIssuedAt(NumericDate.now()); claims.setExpirationTimeMinutesInTheFuture(expireMillis / 1000f / 60f); // 转分钟 JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(new javax.crypto.spec.SecretKeySpec( secret.getBytes(StandardCharsets.UTF_8), "HmacSha256" )); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256); return jws.getCompactSerialization(); } /** * 校验并解析手机号 */ public String parseMobile(String token) throws Exception { var claims = this.parse(token); return claims.getSubject(); } public JwtClaims parse(String token) throws Exception { JwtConsumer consumer = new JwtConsumerBuilder() .setRequireExpirationTime() .setRequireSubject() .setVerificationKey( new javax.crypto.spec.SecretKeySpec( secret.getBytes(StandardCharsets.UTF_8), "HmacSha256" ) ) .build(); return consumer.processToClaims(token); } }