50 lines
1.4 KiB
Java
50 lines
1.4 KiB
Java
package com.example.keycloakpattern;
|
|
|
|
import static org.assertj.core.api.Assertions.assertThat;
|
|
|
|
import java.time.Instant;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
import org.junit.jupiter.api.Test;
|
|
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
|
import org.springframework.security.oauth2.jwt.Jwt;
|
|
|
|
class AudienceValidatorTest {
|
|
|
|
private final AudienceValidator validator =
|
|
new AudienceValidator("keycloak-pattern-api");
|
|
|
|
@Test
|
|
void acceptsRequiredAudience() {
|
|
OAuth2TokenValidatorResult result = validator.validate(jwtWithAudience(
|
|
List.of("account", "keycloak-pattern-api")
|
|
));
|
|
|
|
assertThat(result.hasErrors()).isFalse();
|
|
}
|
|
|
|
@Test
|
|
void rejectsForeignAudience() {
|
|
OAuth2TokenValidatorResult result = validator.validate(jwtWithAudience(
|
|
List.of("another-resource")
|
|
));
|
|
|
|
assertThat(result.hasErrors()).isTrue();
|
|
assertThat(result.getErrors())
|
|
.extracting(error -> error.getErrorCode())
|
|
.containsExactly("invalid_token");
|
|
}
|
|
|
|
private Jwt jwtWithAudience(List<String> audience) {
|
|
Instant now = Instant.now();
|
|
return new Jwt(
|
|
"test-token",
|
|
now,
|
|
now.plusSeconds(300),
|
|
Map.of("alg", "none"),
|
|
Map.of("sub", "test-subject", "aud", audience)
|
|
);
|
|
}
|
|
}
|