findme-backend-merchant-java/src/main/java/com/xjhs/findmemerchant/security/JwtTokenService.java
2026-01-09 12:20:44 +08:00

61 lines
2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
}