Polish gh-201

This commit is contained in:
Joe Grandja 2021-01-29 08:21:38 -05:00
parent aeab08579a
commit 3f310eec00
5 changed files with 101 additions and 168 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2020 the original author or authors.
* 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.

View File

@ -87,13 +87,12 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
private RequestMatcher tokenRevocationEndpointMatcher;
private RequestMatcher jwkSetEndpointMatcher;
private RequestMatcher oidcProviderConfigurationEndpointMatcher;
private final RequestMatcher endpointsMatcher = request -> {
return this.authorizationEndpointMatcher.matches(request) ||
private final RequestMatcher endpointsMatcher = (request) ->
this.authorizationEndpointMatcher.matches(request) ||
this.tokenEndpointMatcher.matches(request) ||
this.tokenRevocationEndpointMatcher.matches(request) ||
this.jwkSetEndpointMatcher.matches(request) ||
this.oidcProviderConfigurationEndpointMatcher.matches(request);
};
/**
* Sets the repository of registered clients.
@ -242,16 +241,6 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
builder.addFilterAfter(postProcess(tokenRevocationEndpointFilter), OAuth2TokenEndpointFilter.class);
}
private static void validateProviderSettings(ProviderSettings providerSettings) {
if (providerSettings.issuer() != null) {
try {
new URI(providerSettings.issuer()).toURL();
} catch (Exception ex) {
throw new IllegalArgumentException("issuer must be a valid URL", ex);
}
}
}
private void initEndpointMatchers(ProviderSettings providerSettings) {
this.authorizationEndpointMatcher = new OrRequestMatcher(
new AntPathRequestMatcher(
@ -270,6 +259,16 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI, HttpMethod.GET.name());
}
private static void validateProviderSettings(ProviderSettings providerSettings) {
if (providerSettings.issuer() != null) {
try {
new URI(providerSettings.issuer()).toURL();
} catch (Exception ex) {
throw new IllegalArgumentException("issuer must be a valid URL", ex);
}
}
}
private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepository(B builder) {
RegisteredClientRepository registeredClientRepository = builder.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) {

View File

@ -15,18 +15,14 @@
*/
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 com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
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;
@ -41,12 +37,16 @@ import org.springframework.security.oauth2.server.authorization.config.ProviderS
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;
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;
/**
* Integration tests for the JWK Set requests.
* Integration tests for the JWK Set endpoint.
*
* @author Florian Berthe
*/
@ -78,32 +78,26 @@ public class JwkSetTests {
}
@Test
public void requestWhenJwkSetValidThenReturnKeys() throws Exception {
public void requestWhenJwkSetThenReturnKeys() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
this.mvc.perform(get(NimbusJwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI))
assertJwkSetRequestThenReturnKeys(NimbusJwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI);
}
@Test
public void requestWhenJwkSetCustomEndpointThenReturnKeys() throws Exception {
this.spring.register(AuthorizationServerConfigurationCustomEndpoints.class).autowire();
assertJwkSetRequestThenReturnKeys(providerSettings.jwkSetEndpoint());
}
private void assertJwkSetRequestThenReturnKeys(String jwkSetEndpointUri) throws Exception {
this.mvc.perform(get(jwkSetEndpointUri))
.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
@ -128,7 +122,7 @@ public class JwkSetTests {
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
static class AuthorizationServerConfigurationCustomEndpoints extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {

View File

@ -58,7 +58,6 @@ import org.springframework.security.oauth2.server.authorization.web.OAuth2Author
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
@ -114,7 +113,9 @@ public class OAuth2AuthorizationCodeGrantTests {
jwtEncoder = new NimbusJwsEncoder(jwkSource);
jwtCustomizer = mock(BiConsumer.class);
jwtEncoder.setJwtCustomizer(jwtCustomizer);
providerSettings = new ProviderSettings().authorizationEndpoint("/test/authorize").tokenEndpoint("/test/token");
providerSettings = new ProviderSettings()
.authorizationEndpoint("/test/authorize")
.tokenEndpoint("/test/token");
}
@Before
@ -131,7 +132,7 @@ public class OAuth2AuthorizationCodeGrantTests {
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
MvcResult mvcResult = this.mvc.perform(get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
.params(getAuthorizationRequestParameters(registeredClient)))
.andExpect(status().is3xxRedirection())
.andReturn();
@ -145,11 +146,22 @@ public class OAuth2AuthorizationCodeGrantTests {
public void requestWhenAuthorizationRequestAuthenticatedThenRedirectToClient() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
assertAuthorizationRequestRedirectsToClient(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI);
}
@Test
public void requestWhenAuthorizationRequestCustomEndpointThenRedirectToClient() throws Exception {
this.spring.register(AuthorizationServerConfigurationCustomEndpoints.class).autowire();
assertAuthorizationRequestRedirectsToClient(providerSettings.authorizationEndpoint());
}
private void assertAuthorizationRequestRedirectsToClient(String authorizationEndpointUri) throws Exception {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
MvcResult mvcResult = this.mvc.perform(get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
MvcResult mvcResult = this.mvc.perform(get(authorizationEndpointUri)
.params(getAuthorizationRequestParameters(registeredClient))
.with(user("user")))
.andExpect(status().is3xxRedirection())
@ -160,32 +172,6 @@ public class OAuth2AuthorizationCodeGrantTests {
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
public void requestWhenTokenRequestValidThenReturnAccessTokenResponse() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
@ -200,7 +186,32 @@ public class OAuth2AuthorizationCodeGrantTests {
eq(TokenType.AUTHORIZATION_CODE)))
.thenReturn(authorization);
this.mvc.perform(post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI)
assertTokenRequestReturnsAccessTokenResponse(
registeredClient, authorization, OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI);
}
@Test
public void requestWhenTokenRequestCustomEndpointThenReturnAccessTokenResponse() throws Exception {
this.spring.register(AuthorizationServerConfigurationCustomEndpoints.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);
assertTokenRequestReturnsAccessTokenResponse(
registeredClient, authorization, providerSettings.tokenEndpoint());
}
private void assertTokenRequestReturnsAccessTokenResponse(RegisteredClient registeredClient,
OAuth2Authorization authorization, String tokenEndpointUri) throws Exception {
this.mvc.perform(post(tokenEndpointUri)
.params(getTokenRequestParameters(registeredClient, authorization))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
@ -288,48 +299,6 @@ public class OAuth2AuthorizationCodeGrantTests {
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) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue());
@ -390,7 +359,7 @@ public class OAuth2AuthorizationCodeGrantTests {
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
static class AuthorizationServerConfigurationCustomEndpoints extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {

View File

@ -50,7 +50,6 @@ import org.springframework.security.oauth2.server.authorization.client.TestRegis
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@ -61,6 +60,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
@ -108,7 +108,7 @@ public class OAuth2TokenRevocationTests {
TokenType tokenType = TokenType.REFRESH_TOKEN;
when(authorizationService.findByToken(eq(token.getTokenValue()), isNull())).thenReturn(authorization);
this.mvc.perform(MockMvcRequestBuilders.post(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI)
this.mvc.perform(post(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI)
.params(getTokenRevocationRequestParameters(token, tokenType))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
@ -131,6 +131,17 @@ public class OAuth2TokenRevocationTests {
public void requestWhenRevokeAccessTokenThenRevoked() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
assertRevokeAccessTokenThenRevoked(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI);
}
@Test
public void requestWhenRevokeAccessTokenCustomEndpointThenRevoked() throws Exception {
this.spring.register(AuthorizationServerConfigurationCustomEndpoints.class).autowire();
assertRevokeAccessTokenThenRevoked(providerSettings.tokenRevocationEndpoint());
}
private void assertRevokeAccessTokenThenRevoked(String tokenRevocationEndpointUri) throws Exception {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
@ -140,7 +151,7 @@ public class OAuth2TokenRevocationTests {
TokenType tokenType = TokenType.ACCESS_TOKEN;
when(authorizationService.findByToken(eq(token.getTokenValue()), isNull())).thenReturn(authorization);
this.mvc.perform(MockMvcRequestBuilders.post(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI)
this.mvc.perform(post(tokenRevocationEndpointUri)
.params(getTokenRevocationRequestParameters(token, tokenType))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
@ -159,46 +170,6 @@ public class OAuth2TokenRevocationTests {
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) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames2.TOKEN, token.getTokenValue());
@ -236,7 +207,7 @@ public class OAuth2TokenRevocationTests {
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithProviderSettings extends AuthorizationServerConfiguration {
static class AuthorizationServerConfigurationCustomEndpoints extends AuthorizationServerConfiguration {
@Bean
ProviderSettings providerSettings() {