1
This commit is contained in:
59
backend/src/main/java/com/example/demo/auth/JwtService.java
Normal file
59
backend/src/main/java/com/example/demo/auth/JwtService.java
Normal 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user