This commit is contained in:
2025-09-24 20:35:15 +08:00
parent 39679f7330
commit 8a458ff0a4
12033 changed files with 1537546 additions and 13292 deletions

View File

@@ -0,0 +1,59 @@
package com.example.demo.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@Service
public class JwtService {
private final JwtProperties props;
public JwtService(JwtProperties props) {
this.props = props;
}
public String signToken(Long userId, Long shopId, String phone, String provider) {
Instant now = Instant.now();
Algorithm alg = Algorithm.HMAC256(props.getSecret() == null ? "dev-secret" : props.getSecret());
var jwt = JWT.create()
.withIssuer(props.getIssuer())
.withIssuedAt(java.util.Date.from(now))
.withExpiresAt(java.util.Date.from(now.plusSeconds(props.getTtlSeconds())))
.withClaim("userId", userId)
.withClaim("shopId", shopId)
.withClaim("provider", provider);
if (phone != null && !phone.isBlank()) jwt.withClaim("phone", phone);
return jwt.sign(alg);
}
public Map<String,Object> parseClaims(String authorizationHeader) {
Map<String,Object> out = new HashMap<>();
if (authorizationHeader == null || authorizationHeader.isBlank()) return out;
String prefix = "Bearer ";
if (!authorizationHeader.startsWith(prefix)) return out;
String token = authorizationHeader.substring(prefix.length()).trim();
try {
Algorithm alg = Algorithm.HMAC256(props.getSecret() == null ? "dev-secret" : props.getSecret());
JWTVerifier verifier = JWT.require(alg)
.withIssuer(props.getIssuer())
.acceptLeeway(props.getClockSkewSeconds())
.build();
DecodedJWT jwt = verifier.verify(token);
Long userId = jwt.getClaim("userId").asLong();
Long shopId = jwt.getClaim("shopId").asLong();
String phone = jwt.getClaim("phone").asString();
if (userId != null) out.put("userId", userId);
if (shopId != null) out.put("shopId", shopId);
if (phone != null && !phone.isBlank()) out.put("phone", phone);
} catch (Exception ignore) { }
return out;
}
}