Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom token validators for OAuth2 Resource Server auto-configuration #35874

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
* @author HaiTao Zhang
* @author Anastasiia Losieva
* @author Mushtaq Ahmed
* @author Roman Golovin
*/
@Configuration(proxyBeanMethods = false)
class ReactiveOAuth2ResourceServerJwkConfiguration {
Expand All @@ -71,8 +72,12 @@ static class JwtConfiguration {

private final OAuth2ResourceServerProperties.Jwt properties;

JwtConfiguration(OAuth2ResourceServerProperties properties) {
private final List<OAuth2TokenValidator<Jwt>> customOAuth2TokenValidators;

JwtConfiguration(OAuth2ResourceServerProperties properties,
List<OAuth2TokenValidator<Jwt>> customOAuth2TokenValidators) {
this.properties = properties.getJwt();
this.customOAuth2TokenValidators = customOAuth2TokenValidators;
}

@Bean
Expand All @@ -97,14 +102,17 @@ private void jwsAlgorithms(Set<SignatureAlgorithm> signatureAlgorithms) {
}

private OAuth2TokenValidator<Jwt> getValidators(OAuth2TokenValidator<Jwt> defaultValidator) {
List<String> audiences = this.properties.getAudiences();
if (CollectionUtils.isEmpty(audiences)) {
return defaultValidator;
}
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(defaultValidator);
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
validators.addAll(this.customOAuth2TokenValidators);
List<String> audiences = this.properties.getAudiences();
if (!CollectionUtils.isEmpty(audiences)) {
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
}
if (validators.size() == 1) {
return validators.get(0);
}
return new DelegatingOAuth2TokenValidator<>(validators);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there are no audiences and no custom validators, we should return the defaultValidator rather than creating a DelegatingOAuth2TokenValidator with a single delegate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a check for number of validators in the list to avoid duplication of the CollectionUtils.isEmpty(audiences) check. I think this way it will be easier to add new predefined validators like the one for audiences if needed.

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
* @author Artsiom Yudovin
* @author HaiTao Zhang
* @author Mushtaq Ahmed
* @author Roman Golovin
*/
@Configuration(proxyBeanMethods = false)
class OAuth2ResourceServerJwtConfiguration {
Expand All @@ -72,8 +73,12 @@ static class JwtDecoderConfiguration {

private final OAuth2ResourceServerProperties.Jwt properties;

JwtDecoderConfiguration(OAuth2ResourceServerProperties properties) {
private final List<OAuth2TokenValidator<Jwt>> customOAuth2TokenValidators;

JwtDecoderConfiguration(OAuth2ResourceServerProperties properties,
List<OAuth2TokenValidator<Jwt>> customOAuth2TokenValidators) {
this.properties = properties.getJwt();
this.customOAuth2TokenValidators = customOAuth2TokenValidators;
}

@Bean
Expand All @@ -97,14 +102,17 @@ private void jwsAlgorithms(Set<SignatureAlgorithm> signatureAlgorithms) {
}

private OAuth2TokenValidator<Jwt> getValidators(OAuth2TokenValidator<Jwt> defaultValidator) {
List<String> audiences = this.properties.getAudiences();
if (CollectionUtils.isEmpty(audiences)) {
return defaultValidator;
}
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(defaultValidator);
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
validators.addAll(this.customOAuth2TokenValidators);
List<String> audiences = this.properties.getAudiences();
if (!CollectionUtils.isEmpty(audiences)) {
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
}
if (validators.size() == 1) {
return validators.get(0);
}
return new DelegatingOAuth2TokenValidator<>(validators);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there are no audiences and no custom validators, we should return the defaultValidator rather than creating a DelegatingOAuth2TokenValidator with a single delegate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a check for number of validators in the list to avoid duplication of the CollectionUtils.isEmpty(audiences) check. I think this way it will be easier to add new predefined validators like the one for audiences if needed.

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.core.JsonProcessingException;
Expand Down Expand Up @@ -87,6 +89,7 @@
* @author HaiTao Zhang
* @author Anastasiia Losieva
* @author Mushtaq Ahmed
* @author Roman Golovin
*/
class ReactiveOAuth2ResourceServerAutoConfigurationTests {

Expand Down Expand Up @@ -502,36 +505,73 @@ void autoConfigurationShouldConfigureIssuerAndAudienceJwtValidatorIfPropertyProv
.run((context) -> {
assertThat(context).hasSingleBean(ReactiveJwtDecoder.class);
ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class);
validate(issuerUri, reactiveJwtDecoder);
validate(issuerUri, reactiveJwtDecoder, null);
});
}

@SuppressWarnings("unchecked")
private void validate(String issuerUri, ReactiveJwtDecoder jwtDecoder) throws MalformedURLException {
@Test
void autoConfigurationShouldConfigureAudienceAndCustomValidatorsIfPropertyProvidedAndIssuerUri() throws Exception {
this.server = new MockWebServer();
this.server.start();
String path = "test";
String issuer = this.server.url(path).toString();
String cleanIssuerPath = cleanIssuerPath(issuer);
setupMockResponse(cleanIssuerPath);
String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path;
this.contextRunner.withPropertyValues(
"spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com",
"spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri,
"spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com")
.withUserConfiguration(CustomTokenValidatorsConfig.class)
.run((context) -> {
assertThat(context).hasSingleBean(ReactiveJwtDecoder.class);
ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class);
assertThat(context).hasBean("customJwtClaimValidator");
OAuth2TokenValidator<Jwt> customValidator = (OAuth2TokenValidator<Jwt>) context
.getBean("customJwtClaimValidator");
validate(issuerUri, reactiveJwtDecoder, customValidator);
});
}

@SuppressWarnings("unchecked")
private void validate(String issuerUri, ReactiveJwtDecoder jwtDecoder, OAuth2TokenValidator<Jwt> customValidator)
throws MalformedURLException {
DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils
.getField(jwtDecoder, "jwtValidator");
Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com"));
if (issuerUri != null) {
builder.claim("iss", new URL(issuerUri));
}
if (customValidator != null) {
builder.claim("custom_claim", "custom_claim_value");
}
Jwt jwt = builder.build();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
Collection<OAuth2TokenValidator<Jwt>> delegates = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils
.getField(jwtValidator, "tokenValidators");
validateDelegates(issuerUri, delegates);
validateDelegates(issuerUri, delegates, customValidator);
}

@SuppressWarnings("unchecked")
private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator<Jwt>> delegates) {
private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator<Jwt>> delegates,
OAuth2TokenValidator<Jwt> customValidator) {
assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class);
OAuth2TokenValidator<Jwt> delegatingValidator = delegates.stream()
.filter((v) -> v instanceof DelegatingOAuth2TokenValidator)
.findFirst()
.get();
Collection<OAuth2TokenValidator<Jwt>> nestedDelegates = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils
.getField(delegatingValidator, "tokenValidators");
if (issuerUri != null) {
assertThat(nestedDelegates).hasAtLeastOneElementOfType(JwtIssuerValidator.class);
assertThat(delegatingValidator).extracting("tokenValidators")
.asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class))
.hasAtLeastOneElementOfType(JwtIssuerValidator.class);
}
List<OAuth2TokenValidator<Jwt>> claimValidators = delegates.stream()
.filter((d) -> d instanceof JwtClaimValidator<?>)
.collect(Collectors.toList());
assertThat(claimValidators).anyMatch((v) -> "aud".equals(ReflectionTestUtils.getField(v, "claim")));
if (customValidator != null) {
assertThat(claimValidators)
.anyMatch((v) -> "custom_claim".equals(ReflectionTestUtils.getField(v, "claim")));
}
}

Expand All @@ -552,7 +592,7 @@ void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndIssue
Mono<ReactiveJwtDecoder> jwtDecoderSupplier = (Mono<ReactiveJwtDecoder>) ReflectionTestUtils
.getField(supplierJwtDecoderBean, "jwtDecoderMono");
ReactiveJwtDecoder jwtDecoder = jwtDecoderSupplier.block();
validate(issuerUri, jwtDecoder);
validate(issuerUri, jwtDecoder, null);
});
}

Expand All @@ -570,7 +610,7 @@ void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndPubli
.run((context) -> {
assertThat(context).hasSingleBean(ReactiveJwtDecoder.class);
ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class);
validate(null, jwtDecoder);
validate(null, jwtDecoder, null);
});
}

Expand Down Expand Up @@ -740,4 +780,14 @@ SecurityWebFilterChain testSpringSecurityFilterChain(ServerHttpSecurity http) {

}

@Configuration(proxyBeanMethods = false)
static class CustomTokenValidatorsConfig {

@Bean
JwtClaimValidator<String> customJwtClaimValidator() {
return new JwtClaimValidator<>("custom_claim", "custom_claim_value"::equals);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -80,6 +81,7 @@
* @author Artsiom Yudovin
* @author HaiTao Zhang
* @author Mushtaq Ahmed
* @author Roman Golovin
*/
class OAuth2ResourceServerAutoConfigurationTests {

Expand Down Expand Up @@ -515,7 +517,7 @@ void autoConfigurationShouldConfigureAudienceAndIssuerJwtValidatorIfPropertyProv
.run((context) -> {
assertThat(context).hasSingleBean(JwtDecoder.class);
JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class);
validate(issuerUri, jwtDecoder);
validate(issuerUri, jwtDecoder, null);
});
}

Expand All @@ -536,26 +538,56 @@ void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndIssue
Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils
.getField(supplierJwtDecoderBean, "delegate");
JwtDecoder jwtDecoder = jwtDecoderSupplier.get();
validate(issuerUri, jwtDecoder);
validate(issuerUri, jwtDecoder, null);
});
}

@SuppressWarnings("unchecked")
private void validate(String issuerUri, JwtDecoder jwtDecoder) throws MalformedURLException {
@Test
void autoConfigurationShouldConfigureAudienceAndCustomValidatorsIfPropertyProvidedAndIssuerUri() throws Exception {
this.server = new MockWebServer();
this.server.start();
String path = "test";
String issuer = this.server.url(path).toString();
String cleanIssuerPath = cleanIssuerPath(issuer);
setupMockResponse(cleanIssuerPath);
String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path;
this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri,
"spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com")
.withUserConfiguration(CustomTokenValidatorsConfig.class)
.run((context) -> {
SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class);
Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils
.getField(supplierJwtDecoderBean, "delegate");
JwtDecoder jwtDecoder = jwtDecoderSupplier.get();
assertThat(context).hasBean("customJwtClaimValidator");
OAuth2TokenValidator<Jwt> customValidator = (OAuth2TokenValidator<Jwt>) context
.getBean("customJwtClaimValidator");
validate(issuerUri, jwtDecoder, customValidator);
});
}

@SuppressWarnings("unchecked")
private void validate(String issuerUri, JwtDecoder jwtDecoder, OAuth2TokenValidator<Jwt> customValidator)
throws MalformedURLException {
DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils
.getField(jwtDecoder, "jwtValidator");
Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com"));
if (issuerUri != null) {
builder.claim("iss", new URL(issuerUri));
}
if (customValidator != null) {
builder.claim("custom_claim", "custom_claim_value");
}
Jwt jwt = builder.build();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
Collection<OAuth2TokenValidator<Jwt>> delegates = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils
.getField(jwtValidator, "tokenValidators");
validateDelegates(issuerUri, delegates);
validateDelegates(issuerUri, delegates, customValidator);
}

private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator<Jwt>> delegates) {
private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator<Jwt>> delegates,
OAuth2TokenValidator<Jwt> customValidator) {
assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class);
OAuth2TokenValidator<Jwt> delegatingValidator = delegates.stream()
.filter((v) -> v instanceof DelegatingOAuth2TokenValidator)
Expand All @@ -566,6 +598,14 @@ private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator
.asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class))
.hasAtLeastOneElementOfType(JwtIssuerValidator.class);
}
List<OAuth2TokenValidator<Jwt>> claimValidators = delegates.stream()
.filter((d) -> d instanceof JwtClaimValidator<?>)
.collect(Collectors.toList());
assertThat(claimValidators).anyMatch((v) -> "aud".equals(ReflectionTestUtils.getField(v, "claim")));
if (customValidator != null) {
assertThat(claimValidators)
.anyMatch((v) -> "custom_claim".equals(ReflectionTestUtils.getField(v, "claim")));
}
}

@Test
Expand All @@ -582,7 +622,7 @@ void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndPubli
.run((context) -> {
assertThat(context).hasSingleBean(JwtDecoder.class);
JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class);
validate(null, jwtDecoder);
validate(null, jwtDecoder, null);
});
}

Expand Down Expand Up @@ -745,4 +785,14 @@ SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception

}

@Configuration(proxyBeanMethods = false)
static class CustomTokenValidatorsConfig {

@Bean
JwtClaimValidator<String> customJwtClaimValidator() {
return new JwtClaimValidator<>("custom_claim", "custom_claim_value"::equals);
}

}

}