Add jwt token parsing
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
package com.litoralregas.backend_gateway.auth;
|
||||
|
||||
import com.litoralregas.backend_gateway.security.JwtService;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/debug/jwt")
|
||||
public class JwtDebugController {
|
||||
|
||||
private final JwtService jwtService;
|
||||
|
||||
public JwtDebugController(JwtService jwtService) {
|
||||
this.jwtService = jwtService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public Map<String, Object> debug(@RequestBody String token) {
|
||||
|
||||
return Map.of(
|
||||
"valid", jwtService.isValid(token),
|
||||
"username", jwtService.extractUsername(token),
|
||||
"clientId", jwtService.extractClientId(token),
|
||||
"role", jwtService.extractRole(token)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.litoralregas.backend_gateway.security;
|
||||
|
||||
import com.litoralregas.backend_gateway.user.UserEntity;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -39,4 +41,46 @@ public class JwtService {
|
||||
jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
|
||||
private Claims getClaims(String token) {
|
||||
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
public boolean isValid(String token) {
|
||||
|
||||
try {
|
||||
getClaims(token);
|
||||
return true;
|
||||
} catch (JwtException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return getClaims(token).getSubject();
|
||||
}
|
||||
|
||||
public Long extractClientId(String token) {
|
||||
|
||||
Object value = getClaims(token).get("clientId");
|
||||
|
||||
if (value instanceof Integer integer) {
|
||||
return integer.longValue();
|
||||
}
|
||||
|
||||
if (value instanceof Long longValue) {
|
||||
return longValue;
|
||||
}
|
||||
|
||||
return Long.parseLong(value.toString());
|
||||
}
|
||||
|
||||
public String extractRole(String token) {
|
||||
return getClaims(token).get("role", String.class);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user