This commit is contained in:
Zuev
2026-10-02 04:07:56 +03:00
parent 97bf3cc50a
commit fc5801d683
42 changed files with 1201 additions and 305 deletions

View File

@@ -85,7 +85,11 @@ public class JwtTokenService {
Long userId = asLong(jwt.getClaim("userId")).orElseGet(() -> Long.valueOf(jwt.getSubject()));
String username = jwt.getClaimAsString("username");
Role role = Role.valueOf(jwt.getClaimAsString("role"));
String roleClaim = jwt.getClaimAsString("role");
if (userId <= 0 || username == null || username.isBlank() || roleClaim == null) {
return Optional.empty();
}
Role role = Role.valueOf(roleClaim);
Long departmentId = asLong(jwt.getClaim("departmentId")).orElse(null);
return Optional.of(new AuthenticatedUser(userId, username, role, departmentId));

View File

@@ -59,6 +59,42 @@ class JwtTokenServiceTest {
assertThat(service.authenticate(token, "magistr")).isEmpty();
}
@Test
void rejectsTokenWithMissingRole() throws JOSEException {
String secret = "12345678901234567890123456789012";
JwtTokenService service = new JwtTokenService(properties(secret, Duration.ofMinutes(15)));
assertThat(service.authenticate(signedToken(secret, null, "admin", 10L), "magistr")).isEmpty();
}
@Test
void rejectsTokenWithMissingUsername() throws JOSEException {
String secret = "12345678901234567890123456789012";
JwtTokenService service = new JwtTokenService(properties(secret, Duration.ofMinutes(15)));
assertThat(service.authenticate(signedToken(secret, "ADMIN", null, 10L), "magistr")).isEmpty();
}
@Test
void rejectsTokenWithInvalidUserId() throws JOSEException {
String secret = "12345678901234567890123456789012";
JwtTokenService service = new JwtTokenService(properties(secret, Duration.ofMinutes(15)));
assertThat(service.authenticate(signedToken(secret, "ADMIN", "admin", -1L), "magistr")).isEmpty();
}
private String signedToken(String secret, String role, String username, long userId) throws JOSEException {
JWTClaimsSet claims = new JWTClaimsSet.Builder()
.issuer("magistr")
.subject(Long.toString(userId))
.expirationTime(Date.from(Instant.now().plusSeconds(900)))
.claim("tenant", "magistr")
.claim("userId", userId)
.claim("username", username)
.claim("role", role)
.build();
SignedJWT jwt = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims);
jwt.sign(new MACSigner(secret.getBytes(StandardCharsets.UTF_8)));
return jwt.serialize();
}
private String expiredToken(String secret) {
try {
Instant now = Instant.now();