Use configuration from ProviderSettings in OAuth2AuthorizationServerConfigurer

Closes gh-182
This commit is contained in:
Florian Berthe 2021-01-05 09:53:21 +01:00 committed by Joe Grandja
parent 8e5e5873f5
commit aeab08579a
5 changed files with 320 additions and 31 deletions

View File

@ -22,7 +22,6 @@ import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
/** /**
@ -46,15 +45,15 @@ public class OAuth2AuthorizationServerConfiguration {
public static void applyDefaultSecurity(HttpSecurity http) throws Exception { public static void applyDefaultSecurity(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer = OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer<>(); new OAuth2AuthorizationServerConfigurer<>();
RequestMatcher[] endpointMatchers = authorizationServerConfigurer RequestMatcher endpointsMatcher = authorizationServerConfigurer
.getEndpointMatchers().toArray(new RequestMatcher[0]); .getEndpointsMatcher();
http http
.requestMatcher(new OrRequestMatcher(endpointMatchers)) .requestMatcher(endpointsMatcher)
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated() authorizeRequests.anyRequest().authenticated()
) )
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointMatchers)) .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
.apply(authorizationServerConfigurer); .apply(authorizationServerConfigurer);
} }
// @formatter:on // @formatter:on

View File

@ -16,9 +16,7 @@
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization; package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
import java.net.URI; import java.net.URI;
import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.jwk.source.JWKSource;
@ -84,21 +82,18 @@ import org.springframework.util.StringUtils;
public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBuilder<B>> public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBuilder<B>>
extends AbstractHttpConfigurer<OAuth2AuthorizationServerConfigurer<B>, B> { extends AbstractHttpConfigurer<OAuth2AuthorizationServerConfigurer<B>, B> {
private final RequestMatcher authorizationEndpointMatcher = new OrRequestMatcher( private RequestMatcher authorizationEndpointMatcher;
new AntPathRequestMatcher( private RequestMatcher tokenEndpointMatcher;
OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI, private RequestMatcher tokenRevocationEndpointMatcher;
HttpMethod.GET.name()), private RequestMatcher jwkSetEndpointMatcher;
new AntPathRequestMatcher( private RequestMatcher oidcProviderConfigurationEndpointMatcher;
OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI, private final RequestMatcher endpointsMatcher = request -> {
HttpMethod.POST.name())); return this.authorizationEndpointMatcher.matches(request) ||
private final RequestMatcher tokenEndpointMatcher = new AntPathRequestMatcher( this.tokenEndpointMatcher.matches(request) ||
OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI, HttpMethod.POST.name()); this.tokenRevocationEndpointMatcher.matches(request) ||
private final RequestMatcher tokenRevocationEndpointMatcher = new AntPathRequestMatcher( this.jwkSetEndpointMatcher.matches(request) ||
OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI, HttpMethod.POST.name()); this.oidcProviderConfigurationEndpointMatcher.matches(request);
private final RequestMatcher jwkSetEndpointMatcher = new AntPathRequestMatcher( };
NimbusJwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI, HttpMethod.GET.name());
private final RequestMatcher oidcProviderConfigurationEndpointMatcher = new AntPathRequestMatcher(
OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI, HttpMethod.GET.name());
/** /**
* Sets the repository of registered clients. * Sets the repository of registered clients.
@ -137,21 +132,19 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
} }
/** /**
* Returns a {@code List} of {@link RequestMatcher}'s for the authorization server endpoints. * Returns a {@link RequestMatcher} for the authorization server endpoints.
* *
* @return a {@code List} of {@link RequestMatcher}'s for the authorization server endpoints * @return a {@link RequestMatcher} for the authorization server endpoints
*/ */
public List<RequestMatcher> getEndpointMatchers() { public RequestMatcher getEndpointsMatcher() {
// TODO Initialize matchers using URI's from ProviderSettings return this.endpointsMatcher;
return Arrays.asList(this.authorizationEndpointMatcher, this.tokenEndpointMatcher,
this.tokenRevocationEndpointMatcher, this.jwkSetEndpointMatcher,
this.oidcProviderConfigurationEndpointMatcher);
} }
@Override @Override
public void init(B builder) { public void init(B builder) {
ProviderSettings providerSettings = getProviderSettings(builder); ProviderSettings providerSettings = getProviderSettings(builder);
validateProviderSettings(providerSettings); validateProviderSettings(providerSettings);
initEndpointMatchers(providerSettings);
OAuth2ClientAuthenticationProvider clientAuthenticationProvider = OAuth2ClientAuthenticationProvider clientAuthenticationProvider =
new OAuth2ClientAuthenticationProvider( new OAuth2ClientAuthenticationProvider(
@ -188,7 +181,9 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
if (exceptionHandling != null) { if (exceptionHandling != null) {
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>(); LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
entryPoints.put( entryPoints.put(
new OrRequestMatcher(this.tokenEndpointMatcher, this.tokenRevocationEndpointMatcher), new OrRequestMatcher(
this.tokenEndpointMatcher,
this.tokenRevocationEndpointMatcher),
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
DelegatingAuthenticationEntryPoint authenticationEntryPoint = DelegatingAuthenticationEntryPoint authenticationEntryPoint =
new DelegatingAuthenticationEntryPoint(entryPoints); new DelegatingAuthenticationEntryPoint(entryPoints);
@ -222,7 +217,9 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
OAuth2ClientAuthenticationFilter clientAuthenticationFilter = OAuth2ClientAuthenticationFilter clientAuthenticationFilter =
new OAuth2ClientAuthenticationFilter( new OAuth2ClientAuthenticationFilter(
authenticationManager, authenticationManager,
new OrRequestMatcher(this.tokenEndpointMatcher, this.tokenRevocationEndpointMatcher)); new OrRequestMatcher(
this.tokenEndpointMatcher,
this.tokenRevocationEndpointMatcher));
builder.addFilterAfter(postProcess(clientAuthenticationFilter), AbstractPreAuthenticatedProcessingFilter.class); builder.addFilterAfter(postProcess(clientAuthenticationFilter), AbstractPreAuthenticatedProcessingFilter.class);
OAuth2AuthorizationEndpointFilter authorizationEndpointFilter = OAuth2AuthorizationEndpointFilter authorizationEndpointFilter =
@ -255,6 +252,24 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
} }
} }
private void initEndpointMatchers(ProviderSettings providerSettings) {
this.authorizationEndpointMatcher = new OrRequestMatcher(
new AntPathRequestMatcher(
providerSettings.authorizationEndpoint(),
HttpMethod.GET.name()),
new AntPathRequestMatcher(
providerSettings.authorizationEndpoint(),
HttpMethod.POST.name()));
this.tokenEndpointMatcher = new AntPathRequestMatcher(
providerSettings.tokenEndpoint(), HttpMethod.POST.name());
this.tokenRevocationEndpointMatcher = new AntPathRequestMatcher(
providerSettings.tokenRevocationEndpoint(), HttpMethod.POST.name());
this.jwkSetEndpointMatcher = new AntPathRequestMatcher(
providerSettings.jwkSetEndpoint(), HttpMethod.GET.name());
this.oidcProviderConfigurationEndpointMatcher = new AntPathRequestMatcher(
OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI, HttpMethod.GET.name());
}
private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepository(B builder) { private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepository(B builder) {
RegisteredClientRepository registeredClientRepository = builder.getSharedObject(RegisteredClientRepository.class); RegisteredClientRepository registeredClientRepository = builder.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) { if (registeredClientRepository == null) {

View File

@ -0,0 +1,139 @@
/*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.web.NimbusJwkSetEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
/**
* Integration tests for the JWK Set requests.
*
* @author Florian Berthe
*/
public class JwkSetTests {
private static RegisteredClientRepository registeredClientRepository;
private static OAuth2AuthorizationService authorizationService;
private static JWKSource<SecurityContext> jwkSource;
private static ProviderSettings providerSettings;
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mvc;
@BeforeClass
public static void init() {
registeredClientRepository = mock(RegisteredClientRepository.class);
authorizationService = mock(OAuth2AuthorizationService.class);
JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK);
jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
providerSettings = new ProviderSettings().jwkSetEndpoint("/test/jwks");
}
@Before
public void setup() {
reset(registeredClientRepository);
reset(authorizationService);
}
@Test
public void requestWhenJwkSetValidThenReturnKeys() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
this.mvc.perform(get(NimbusJwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store")))
.andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache")))
.andExpect(jsonPath("$.keys").isNotEmpty())
.andExpect(jsonPath("$.keys").isArray());
}
@Test
public void requestWhenCustomProviderSettingsThenOk() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
this.mvc.perform(get(providerSettings.jwkSetEndpoint()))
.andExpect(status().isOk());
}
@Test
public void requestWhenCustomProviderSettingsThenNotFound() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
this.mvc.perform(get(NimbusJwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI))
.andExpect(status().isNotFound());
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfiguration {
@Bean
RegisteredClientRepository registeredClientRepository() {
return registeredClientRepository;
}
@Bean
OAuth2AuthorizationService authorizationService() {
return authorizationService;
}
@Bean
JWKSource<SecurityContext> jwkSource() {
return jwkSource;
}
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {
return providerSettings;
}
}
}

View File

@ -52,6 +52,7 @@ import org.springframework.security.oauth2.server.authorization.TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients; import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.token.OAuth2AuthorizationCode; import org.springframework.security.oauth2.server.authorization.token.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
@ -96,6 +97,7 @@ public class OAuth2AuthorizationCodeGrantTests {
private static JWKSource<SecurityContext> jwkSource; private static JWKSource<SecurityContext> jwkSource;
private static NimbusJwsEncoder jwtEncoder; private static NimbusJwsEncoder jwtEncoder;
private static BiConsumer<JoseHeader.Builder, JwtClaimsSet.Builder> jwtCustomizer; private static BiConsumer<JoseHeader.Builder, JwtClaimsSet.Builder> jwtCustomizer;
private static ProviderSettings providerSettings;
@Rule @Rule
public final SpringTestRule spring = new SpringTestRule(); public final SpringTestRule spring = new SpringTestRule();
@ -112,6 +114,7 @@ public class OAuth2AuthorizationCodeGrantTests {
jwtEncoder = new NimbusJwsEncoder(jwkSource); jwtEncoder = new NimbusJwsEncoder(jwkSource);
jwtCustomizer = mock(BiConsumer.class); jwtCustomizer = mock(BiConsumer.class);
jwtEncoder.setJwtCustomizer(jwtCustomizer); jwtEncoder.setJwtCustomizer(jwtCustomizer);
providerSettings = new ProviderSettings().authorizationEndpoint("/test/authorize").tokenEndpoint("/test/token");
} }
@Before @Before
@ -157,6 +160,32 @@ public class OAuth2AuthorizationCodeGrantTests {
verify(authorizationService).save(any()); verify(authorizationService).save(any());
} }
@Test
public void requestWhenAuthorizationRequestAndCustomProviderSettingsThenOk() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
this.mvc.perform(MockMvcRequestBuilders.get(providerSettings.authorizationEndpoint())
.params(getAuthorizationRequestParameters(registeredClient)))
.andExpect(status().is3xxRedirection());
}
@Test
public void requestWhenAuthorizationRequestAndCustomProviderSettingsThenNotFound() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
this.mvc.perform(MockMvcRequestBuilders.get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
.params(getAuthorizationRequestParameters(registeredClient)))
.andExpect(status().isNotFound());
}
@Test @Test
public void requestWhenTokenRequestValidThenReturnAccessTokenResponse() throws Exception { public void requestWhenTokenRequestValidThenReturnAccessTokenResponse() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire(); this.spring.register(AuthorizationServerConfiguration.class).autowire();
@ -259,6 +288,48 @@ public class OAuth2AuthorizationCodeGrantTests {
verify(jwtCustomizer).accept(any(JoseHeader.Builder.class), any(JwtClaimsSet.Builder.class)); verify(jwtCustomizer).accept(any(JoseHeader.Builder.class), any(JwtClaimsSet.Builder.class));
} }
@Test
public void requestWhenCustomProviderSettingsThenOk() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(authorizationService.findByToken(
eq(authorization.getTokens().getToken(OAuth2AuthorizationCode.class).getTokenValue()),
eq(TokenType.AUTHORIZATION_CODE)))
.thenReturn(authorization);
this.mvc.perform(post(providerSettings.tokenEndpoint())
.params(getTokenRequestParameters(registeredClient, authorization))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isOk());
}
@Test
public void requestWhenCustomProviderSettingsThenNotFound() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(authorizationService.findByToken(
eq(authorization.getTokens().getToken(OAuth2AuthorizationCode.class).getTokenValue()),
eq(TokenType.AUTHORIZATION_CODE)))
.thenReturn(authorization);
this.mvc.perform(post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI)
.params(getTokenRequestParameters(registeredClient, authorization))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isNotFound());
}
private static MultiValueMap<String, String> getAuthorizationRequestParameters(RegisteredClient registeredClient) { private static MultiValueMap<String, String> getAuthorizationRequestParameters(RegisteredClient registeredClient) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue()); parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue());
@ -316,4 +387,15 @@ public class OAuth2AuthorizationCodeGrantTests {
return jwtEncoder; return jwtEncoder;
} }
} }
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {
return providerSettings;
}
}
} }

View File

@ -47,6 +47,7 @@ import org.springframework.security.oauth2.server.authorization.TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients; import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -71,6 +72,7 @@ public class OAuth2TokenRevocationTests {
private static RegisteredClientRepository registeredClientRepository; private static RegisteredClientRepository registeredClientRepository;
private static OAuth2AuthorizationService authorizationService; private static OAuth2AuthorizationService authorizationService;
private static JWKSource<SecurityContext> jwkSource; private static JWKSource<SecurityContext> jwkSource;
private static ProviderSettings providerSettings;
@Rule @Rule
public final SpringTestRule spring = new SpringTestRule(); public final SpringTestRule spring = new SpringTestRule();
@ -84,6 +86,7 @@ public class OAuth2TokenRevocationTests {
authorizationService = mock(OAuth2AuthorizationService.class); authorizationService = mock(OAuth2AuthorizationService.class);
JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK); JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK);
jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
providerSettings = new ProviderSettings().tokenRevocationEndpoint("/test/revoke");
} }
@Before @Before
@ -156,6 +159,46 @@ public class OAuth2TokenRevocationTests {
assertThat(updatedAuthorization.getTokens().getTokenMetadata(refreshToken).isInvalidated()).isFalse(); assertThat(updatedAuthorization.getTokens().getTokenMetadata(refreshToken).isInvalidated()).isFalse();
} }
@Test
public void requestWhenCustomProviderSettingsThenOk() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
OAuth2RefreshToken token = authorization.getTokens().getRefreshToken();
TokenType tokenType = TokenType.REFRESH_TOKEN;
when(authorizationService.findByToken(eq(token.getTokenValue()), eq(tokenType))).thenReturn(authorization);
this.mvc.perform(MockMvcRequestBuilders.post(providerSettings.tokenRevocationEndpoint())
.params(getTokenRevocationRequestParameters(token, tokenType))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isOk());
}
@Test
public void requestWhenCustomProviderSettingsThenNotFound() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithProviderSettings.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
OAuth2RefreshToken token = authorization.getTokens().getRefreshToken();
TokenType tokenType = TokenType.REFRESH_TOKEN;
when(authorizationService.findByToken(eq(token.getTokenValue()), eq(tokenType))).thenReturn(authorization);
this.mvc.perform(MockMvcRequestBuilders.post(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI)
.params(getTokenRevocationRequestParameters(token, tokenType))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isNotFound());
}
private static MultiValueMap<String, String> getTokenRevocationRequestParameters(AbstractOAuth2Token token, TokenType tokenType) { private static MultiValueMap<String, String> getTokenRevocationRequestParameters(AbstractOAuth2Token token, TokenType tokenType) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames2.TOKEN, token.getTokenValue()); parameters.set(OAuth2ParameterNames2.TOKEN, token.getTokenValue());
@ -190,4 +233,15 @@ public class OAuth2TokenRevocationTests {
return jwkSource; return jwkSource;
} }
} }
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {
return providerSettings;
}
}
} }