Document JwtClaimValidator

Fixes gh-8076
This commit is contained in:
Josh Cummings 2020-03-04 14:47:44 -07:00
parent 6db921c95d
commit 93b8c656d8
No known key found for this signature in database
GPG Key ID: 49EF60DD7FF83443
2 changed files with 20 additions and 4 deletions

View File

@ -36,7 +36,7 @@ Here's what you'll see in this release:
* OAuth 2.0 Resource Server
** Added support for <<oauth2resourceserver-multitenancy,multiple issuers>>
** Added <<testing-opaque-token,test support for Opaque Tokens>>
** Added https://github.com/spring-projects/spring-security/pull/7962[generic claim validator]
** Added <<oauth2resourceserver-jwt-validation-custom,generic claim validator>>
** Added https://github.com/spring-projects/spring-security/issues/5185[XML support]
** Improved https://github.com/spring-projects/spring-security/pull/7826[bearer token error handling] for JWT and Opaque Token
* SAML 2.0

View File

@ -695,9 +695,19 @@ Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API
[source,java]
----
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
OAuth2TokenValidator<Jwt> audienceValidator() {
return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
}
----
Or, for more control you can implement your own `OAuth2TokenValidator`:
[source,java]
----
static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (jwt.getAudience().contains("messaging")) {
return OAuth2TokenValidatorResult.success();
@ -706,6 +716,12 @@ public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
}
}
}
// ...
OAuth2TokenValidator<Jwt> audienceValidator() {
return new AudienceValidator();
}
----
Then, to add into a resource server, it's a matter of specifying the `JwtDecoder` instance:
@ -717,7 +733,7 @@ JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
JwtDecoders.fromIssuerLocation(issuerUri);
OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);