Implement OpenID Provider Configuration endpoint

- See https://openid.net/specs/openid-connect-discovery-1_0.html
  sections 3 and 4.
- We introduce here a "ProviderSettings" construct to configure
  the authorization server, starting with endpoint paths (e.g.
  token endpoint, jwk set endpont, ...)

Closes gh-55
This commit is contained in:
Daniel Garnier-Moiroux
2020-10-16 14:56:39 +02:00
committed by Joe Grandja
parent 43fbd9d345
commit 6a5e277a11
14 changed files with 2140 additions and 5 deletions

View File

@@ -0,0 +1,139 @@
/*
* Copyright 2020 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 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.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.crypto.key.CryptoKeySource;
import org.springframework.security.crypto.key.StaticKeyGeneratingCryptoKeySource;
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.OidcProviderConfigurationEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for the OpenID Connect.
*
* @author Daniel Garnier-Moiroux
*/
public class OidcTests {
private static final String issuerUrl = "https://example.com/issuer1";
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mvc;
@Test
public void requestWhenIssuerSetAndOpenIDProviderConfigurationRequestThenReturnProviderConfigurationResponse() throws Exception {
this.spring.register(AuthorizationServerConfigurationWithIssuer.class).autowire();
this.mvc.perform(MockMvcRequestBuilders.get(OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("issuer").value(issuerUrl))
.andReturn();
}
@Test
public void requestWhenIssuerNotSetAndOpenIDProviderConfigurationRequestThenRedirectsToLogin() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
MvcResult mvcResult = this.mvc.perform(get(OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI))
.andExpect(status().is3xxRedirection())
.andReturn();
assertThat(mvcResult.getResponse().getRedirectedUrl()).endsWith("/login");
}
@Test
public void requestWhenIssuerNotValidUrlThenThrowException() {
assertThatThrownBy(
() -> this.spring.register(AuthorizationServerConfigurationWithInvalidUrlIssuer.class).autowire()
);
}
@Test
public void requestWhenIssuerNotValidUriThenThrowException() {
assertThatThrownBy(
() -> this.spring.register(AuthorizationServerConfigurationWithInvalidUriIssuer.class).autowire()
);
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfiguration {
@Bean
RegisteredClientRepository registeredClientRepository() {
return mock(RegisteredClientRepository.class);
}
@Bean
CryptoKeySource keySource() {
return new StaticKeyGeneratingCryptoKeySource();
}
@Bean
ProviderSettings providerSettings() {
return new ProviderSettings();
}
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithIssuer extends AuthorizationServerConfiguration {
@Bean
@Override
ProviderSettings providerSettings() {
return new ProviderSettings().issuer(issuerUrl);
}
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithInvalidUrlIssuer extends AuthorizationServerConfiguration {
@Bean
@Override
ProviderSettings providerSettings() {
return new ProviderSettings().issuer("urn:example");
}
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfigurationWithInvalidUriIssuer extends AuthorizationServerConfiguration {
@Bean
@Override
ProviderSettings providerSettings() {
return new ProviderSettings().issuer("https://not a valid uri");
}
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2020 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.oauth2.core.converter;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
/**
* TODO
* This class is temporary and will be removed after upgrading to Spring Security 5.5.0 GA.
* These tests will probably be folded into tests for {@link ClaimConversionService}.
*
* Tests for {@link ObjectToSetStringConverter2}.
*
* @author Daniel Garnier-Moiroux
*/
public class ObjectToSetStringConverter2Test {
@Test
@SuppressWarnings("unchecked")
public void convertFromNullThenReturnNull() {
ObjectToSetStringConverter2 converter = new ObjectToSetStringConverter2();
Set<String> result = (Set<String>) converter.convert(null, null, null);
assertThat(result).isNull();
}
@Test
@SuppressWarnings("unchecked")
public void convertFromStringThenReturnSet() {
ObjectToSetStringConverter2 converter = new ObjectToSetStringConverter2();
Set<String> result = (Set<String>) converter.convert("Hello", null, null);
assertThat(result).containsExactly("Hello");
}
@Test
@SuppressWarnings("unchecked")
public void convertFromSetThenReturnSet() {
ObjectToSetStringConverter2 converter = new ObjectToSetStringConverter2();
Set<String> result = (Set<String>) converter.convert(new HashSet<>(Arrays.asList("Hello", "world")), null, null);
assertThat(result).containsExactlyInAnyOrder("Hello", "world");
}
@Test
@SuppressWarnings("unchecked")
public void convertFromCollectionThenReturnSet() {
ObjectToSetStringConverter2 converter = new ObjectToSetStringConverter2();
Set<String> result = (Set<String>) converter.convert(Arrays.asList("Hello", "world"), null, null);
assertThat(result).containsExactlyInAnyOrder("Hello", "world");
}
@Test
@SuppressWarnings("unchecked")
public void convertFromEmptyCollectionThenReturnEmptySet() {
ObjectToSetStringConverter2 converter = new ObjectToSetStringConverter2();
Set<String> result = (Set<String>) converter.convert(Collections.emptyList(), null, null);
assertThat(result).isEmpty();
}
}

View File

@@ -0,0 +1,208 @@
/*
* Copyright 2020 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.oauth2.core.http.converter;
import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.security.oauth2.core.oidc.OidcProviderConfiguration;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link OidcProviderConfigurationHttpMessageConverter}
*
* @author Daniel Garnier-Moiroux
*/
public class OidcProviderConfigurationHttpMessageConverterTests {
private final OidcProviderConfigurationHttpMessageConverter messageConverter = new OidcProviderConfigurationHttpMessageConverter();
@Test
public void supportsWhenOidcProviderConfigurationThenTrue() {
assertThat(this.messageConverter.supports(OidcProviderConfiguration.class)).isTrue();
}
@Test
public void setProviderConfigurationParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setProviderConfigurationParametersConverter(null));
}
@Test
public void setProviderConfigurationConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setProviderConfigurationConverter(null));
}
@Test
public void readInternalWhenSuccessfulProviderConfigurationOnlyRequiredParametersThenReadOidcProviderConfiguration() throws Exception {
// @formatter:off
String providerConfigurationResponse = "{\n"
+ " \"issuer\": \"https://example.com/issuer1\",\n"
+ " \"authorization_endpoint\": \"https://example.com/issuer1/oauth2/authorize\",\n"
+ " \"token_endpoint\": \"https://example.com/issuer1/oauth2/token\",\n"
+ " \"jwks_uri\": \"https://example.com/issuer1/oauth2/jwks\",\n"
+ " \"response_types_supported\": [\"code\"],\n"
+ " \"subject_types_supported\": [\"public\"]\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(providerConfigurationResponse.getBytes(), HttpStatus.OK);
OidcProviderConfiguration providerConfiguration = this.messageConverter
.readInternal(OidcProviderConfiguration.class, response);
assertThat(providerConfiguration.getIssuer()).isEqualTo(new URL("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(new URL("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(new URL("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(new URL("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getScopes()).isNull();
assertThat(providerConfiguration.getGrantTypes()).isNull();
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).isNull();
}
@Test
public void readInternalWhenSuccessfulProviderConfigurationThenReadOidcProviderConfiguration() throws Exception {
// @formatter:off
String providerConfigurationResponse = "{\n"
+ " \"issuer\": \"https://example.com/issuer1\",\n"
+ " \"authorization_endpoint\": \"https://example.com/issuer1/oauth2/authorize\",\n"
+ " \"token_endpoint\": \"https://example.com/issuer1/oauth2/token\",\n"
+ " \"jwks_uri\": \"https://example.com/issuer1/oauth2/jwks\",\n"
+ " \"scopes_supported\": [\"openid\"],\n"
+ " \"response_types_supported\": [\"code\"],\n"
+ " \"grant_types_supported\": [\"authorization_code\", \"client_credentials\"],\n"
+ " \"subject_types_supported\": [\"public\"],\n"
+ " \"token_endpoint_auth_methods_supported\": [\"basic\"],\n"
+ " \"custom_claim\": \"value\",\n"
+ " \"custom_collection_claim\": [\"value1\", \"value2\"]\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(providerConfigurationResponse.getBytes(), HttpStatus.OK);
OidcProviderConfiguration providerConfiguration = this.messageConverter
.readInternal(OidcProviderConfiguration.class, response);
assertThat(providerConfiguration.getIssuer()).isEqualTo(new URL("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(new URL("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(new URL("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(new URL("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getScopes()).containsExactly("openid");
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getGrantTypes()).containsExactlyInAnyOrder("authorization_code", "client_credentials");
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).containsExactly("basic");
assertThat(providerConfiguration.getClaimAsString("custom_claim")).isEqualTo("value");
assertThat(providerConfiguration.getClaimAsStringList("custom_collection_claim")).containsExactlyInAnyOrder("value1", "value2");
}
@Test
public void readInternalWhenFailingConverterThenThrowException() {
String errorMessage = "this is not a valid converter";
this.messageConverter.setProviderConfigurationConverter(source -> {
throw new RuntimeException(errorMessage);
});
MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class)
.isThrownBy(() -> this.messageConverter.readInternal(OidcProviderConfiguration.class, response))
.withMessageContaining("An error occurred reading the OpenID Provider Configuration")
.withMessageContaining(errorMessage);
}
@Test
public void readInternalWhenInvalidProviderConfigurationThenThrowException() {
String providerConfigurationResponse = "{ \"issuer\": null }";
MockClientHttpResponse response = new MockClientHttpResponse(providerConfigurationResponse.getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class)
.isThrownBy(() -> this.messageConverter.readInternal(OidcProviderConfiguration.class, response))
.withMessageContaining("An error occurred reading the OpenID Provider Configuration")
.withMessageContaining("issuer cannot be null");
}
@Test
public void writeInternalWhenOidcProviderConfigurationThenWriteTokenResponse() throws Exception {
OidcProviderConfiguration providerConfiguration =
OidcProviderConfiguration.withClaims()
.issuer("https://example.com/issuer1")
.authorizationEndpoint("https://example.com/issuer1/oauth2/authorize")
.tokenEndpoint("https://example.com/issuer1/oauth2/token")
.jwksUri("https://example.com/issuer1/oauth2/jwks")
.scope("openid")
.responseType("code")
.grantType("authorization_code")
.grantType("client_credentials")
.subjectType("public")
.tokenEndpointAuthenticationMethod("basic")
.claim("custom_claim", "value")
.claim("custom_collection_claim", Arrays.asList("value1", "value2"))
.build();
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.messageConverter.writeInternal(providerConfiguration, outputMessage);
String providerConfigurationResponse = outputMessage.getBodyAsString();
assertThat(providerConfigurationResponse).contains("\"issuer\":\"https://example.com/issuer1\"");
assertThat(providerConfigurationResponse).contains("\"authorization_endpoint\":\"https://example.com/issuer1/oauth2/authorize\"");
assertThat(providerConfigurationResponse).contains("\"token_endpoint\":\"https://example.com/issuer1/oauth2/token\"");
assertThat(providerConfigurationResponse).contains("\"jwks_uri\":\"https://example.com/issuer1/oauth2/jwks\"");
assertThat(providerConfigurationResponse).contains("\"scopes_supported\":[\"openid\"]");
assertThat(providerConfigurationResponse).contains("\"response_types_supported\":[\"code\"]");
assertThat(providerConfigurationResponse).contains("\"grant_types_supported\":[\"authorization_code\",\"client_credentials\"]");
assertThat(providerConfigurationResponse).contains("\"subject_types_supported\":[\"public\"]");
assertThat(providerConfigurationResponse).contains("\"token_endpoint_auth_methods_supported\":[\"basic\"]");
assertThat(providerConfigurationResponse).contains("\"custom_claim\":\"value\"");
assertThat(providerConfigurationResponse).contains("\"custom_collection_claim\":[\"value1\",\"value2\"]");
}
@Test
@SuppressWarnings("unchecked")
public void writeInternalWhenWriteFailsThenThrowsException() throws MalformedURLException {
String errorMessage = "this is not a valid converter";
Converter<OidcProviderConfiguration, Map<String, Object>> failingConverter =
source -> {
throw new RuntimeException(errorMessage);
};
this.messageConverter.setProviderConfigurationParametersConverter(failingConverter);
OidcProviderConfiguration providerConfiguration =
OidcProviderConfiguration.withClaims()
.issuer("https://example.com")
.authorizationEndpoint("https://example.com")
.tokenEndpoint("https://example.com")
.jwksUri("https://example.com")
.responseType("code")
.subjectType("public")
.build();
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatThrownBy(() -> this.messageConverter.writeInternal(providerConfiguration, outputMessage))
.isInstanceOf(HttpMessageNotWritableException.class)
.hasMessageContaining("An error occurred writing the OpenID Provider Configuration")
.hasMessageContaining(errorMessage);
}
}

View File

@@ -0,0 +1,398 @@
/*
* Copyright 2020 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.oauth2.core.oidc;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link OidcProviderConfiguration}.
*
* @author Daniel Garnier-Moiroux
*/
public class OidcProviderConfigurationTests {
private final OidcProviderConfiguration.Builder minimalConfigurationBuilder =
OidcProviderConfiguration.withClaims()
.issuer("https://example.com/issuer1")
.authorizationEndpoint("https://example.com/issuer1/oauth2/authorize")
.tokenEndpoint("https://example.com/issuer1/oauth2/token")
.jwksUri("https://example.com/issuer1/oauth2/jwks")
.scope("openid")
.responseType("code")
.subjectType("public");
@Test
public void buildWhenAllRequiredClaimsAndAdditionalClaimsThenCreated() {
OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.withClaims()
.issuer("https://example.com/issuer1")
.authorizationEndpoint("https://example.com/issuer1/oauth2/authorize")
.tokenEndpoint("https://example.com/issuer1/oauth2/token")
.jwksUri("https://example.com/issuer1/oauth2/jwks")
.scope("openid")
.responseType("code")
.grantType("authorization_code")
.grantType("client_credentials")
.subjectType("public")
.tokenEndpointAuthenticationMethod("basic")
.claim("a-claim", "a-value")
.build();
assertThat(providerConfiguration.getIssuer()).isEqualTo(url("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(url("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getScopes()).containsExactly("openid");
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getGrantTypes()).containsExactlyInAnyOrder("authorization_code", "client_credentials");
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).containsExactly("basic");
assertThat(providerConfiguration.getClaimAsString("a-claim")).isEqualTo("a-value");
}
@Test
public void buildWhenOnlyRequiredClaimsThenCreated() {
OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.withClaims()
.issuer("https://example.com/issuer1")
.authorizationEndpoint("https://example.com/issuer1/oauth2/authorize")
.tokenEndpoint("https://example.com/issuer1/oauth2/token")
.jwksUri("https://example.com/issuer1/oauth2/jwks")
.scope("openid")
.responseType("code")
.subjectType("public")
.build();
assertThat(providerConfiguration.getIssuer()).isEqualTo(url("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(url("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getScopes()).containsExactly("openid");
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getGrantTypes()).isNull();
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).isNull();
}
@Test
public void buildFromClaimsThenCreated() {
HashMap<String, Object> claims = new HashMap<>();
claims.put(OidcProviderMetadataClaimNames.ISSUER, "https://example.com/issuer1");
claims.put(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, "https://example.com/issuer1/oauth2/authorize");
claims.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, "https://example.com/issuer1/oauth2/token");
claims.put(OidcProviderMetadataClaimNames.JWKS_URI, "https://example.com/issuer1/oauth2/jwks");
claims.put(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, Collections.singleton("openid"));
claims.put(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, Collections.singleton("code"));
claims.put(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, Collections.singleton("public"));
claims.put("some-claim", "some-value");
OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.withClaims(claims).build();
assertThat(providerConfiguration.getIssuer()).isEqualTo(url("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(url("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getScopes()).containsExactly("openid");
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getGrantTypes()).isNull();
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).isNull();
assertThat(providerConfiguration.getClaimAsString("some-claim")).isEqualTo("some-value");
}
@Test
public void buildFromClaimsWhenUsingUrlsThenCreated() {
HashMap<String, Object> claims = new HashMap<>();
claims.put(OidcProviderMetadataClaimNames.ISSUER, url("https://example.com/issuer1"));
claims.put(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, url("https://example.com/issuer1/oauth2/authorize"));
claims.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, url("https://example.com/issuer1/oauth2/token"));
claims.put(OidcProviderMetadataClaimNames.JWKS_URI, url("https://example.com/issuer1/oauth2/jwks"));
claims.put(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, Collections.singleton("openid"));
claims.put(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, Collections.singleton("code"));
claims.put(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, Collections.singleton("public"));
claims.put("some-claim", "some-value");
OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.withClaims(claims).build();
assertThat(providerConfiguration.getIssuer()).isEqualTo(url("https://example.com/issuer1"));
assertThat(providerConfiguration.getAuthorizationEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/authorize"));
assertThat(providerConfiguration.getTokenEndpoint()).isEqualTo(url("https://example.com/issuer1/oauth2/token"));
assertThat(providerConfiguration.getJwksUri()).isEqualTo(url("https://example.com/issuer1/oauth2/jwks"));
assertThat(providerConfiguration.getScopes()).containsExactly("openid");
assertThat(providerConfiguration.getResponseTypes()).containsExactly("code");
assertThat(providerConfiguration.getGrantTypes()).isNull();
assertThat(providerConfiguration.getSubjectTypes()).containsExactly("public");
assertThat(providerConfiguration.getTokenEndpointAuthenticationMethods()).isNull();
assertThat(providerConfiguration.getClaimAsString("some-claim")).isEqualTo("some-value");
}
@Test
public void withClaimsWhenNullThenThrowsException() {
assertThatThrownBy(() -> OidcProviderConfiguration.withClaims(null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void withClaimsWhenMissingRequiredClaimsThenThrowsException() {
assertThatThrownBy(() -> OidcProviderConfiguration.withClaims(Collections.emptyMap()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void buildWhenCalledTwiceThenGeneratesTwoConfigurations() {
OidcProviderConfiguration first = minimalConfigurationBuilder
.grantType("client_credentials")
.build();
OidcProviderConfiguration second = minimalConfigurationBuilder
.claims((claims) ->
{
LinkedHashSet<String> newGrantTypes = new LinkedHashSet<>();
newGrantTypes.add("authorization_code");
newGrantTypes.add("implicit");
claims.put(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, newGrantTypes);
}
)
.build();
assertThat(first.getGrantTypes()).containsExactly("client_credentials");
assertThat(second.getGrantTypes()).containsExactlyInAnyOrder("authorization_code", "implicit");
}
@Test
public void buildWhenMissingIssuerThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.ISSUER));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issuer cannot be null");
}
@Test
public void buildWhenIssuerIsNotAnUrlThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.put(OidcProviderMetadataClaimNames.ISSUER, "not an url"));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("issuer must be a valid URL");
}
@Test
public void buildWhenMissingAuthorizationEndpointThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizationEndpoint cannot be null");
}
@Test
public void buildWhenAuthorizationEndpointIsNotAnUrlThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.put(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, "not an url"));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("authorizationEndpoint must be a valid URL");
}
@Test
public void buildWhenMissingTokenEndpointThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tokenEndpoint cannot be null");
}
@Test
public void buildWhenTokenEndpointIsNotAnUrlThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, "not an url"));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("tokenEndpoint must be a valid URL");
}
@Test
public void buildWhenMissingJwksUriThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.JWKS_URI));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("jwkSetUri cannot be null");
}
@Test
public void buildWheJwksUriIsNotAnUrlThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.put(OidcProviderMetadataClaimNames.JWKS_URI, "not an url"));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("jwkSetUri must be a valid URL");
}
@Test
public void buildWhenMissingResponseTypesThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("responseTypes cannot be empty");
}
@Test
public void buildWhenMissingSubjectTypesThenThrowsException() {
OidcProviderConfiguration.Builder builder = minimalConfigurationBuilder
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED));
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("subjectTypes cannot be empty");
}
@Test
public void responseTypesWhenAddingOrRemovingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.responseType("should-be-removed")
.responseTypes(responseTypes -> {
responseTypes.clear();
responseTypes.add("some-response-type");
})
.build();
assertThat(configuration.getResponseTypes()).containsExactly("some-response-type");
}
@Test
public void responseTypesWhenNotPresentAndAddingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.claims(claims -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED))
.responseTypes(responseTypes -> responseTypes.add("some-response-type"))
.build();
assertThat(configuration.getResponseTypes()).containsExactly("some-response-type");
}
@Test
public void subjectTypesWhenAddingOrRemovingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.subjectType("should-be-removed")
.subjectTypes(subjectTypes -> {
subjectTypes.clear();
subjectTypes.add("some-subject-type");
})
.build();
assertThat(configuration.getSubjectTypes()).containsExactly("some-subject-type");
}
@Test
public void scopesWhenAddingOrRemovingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.scope("should-be-removed")
.scopes(scopes -> {
scopes.clear();
scopes.add("some-scope");
})
.build();
assertThat(configuration.getScopes()).containsExactly("some-scope");
}
@Test
public void grantTypesWhenAddingOrRemovingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.grantType("should-be-removed")
.grantTypes(grantTypes -> {
grantTypes.clear();
grantTypes.add("some-grant-type");
})
.build();
assertThat(configuration.getGrantTypes()).containsExactly("some-grant-type");
}
@Test
public void tokenEndpointAuthenticationMethodsWhenAddingOrRemovingThenCorrectValues() {
OidcProviderConfiguration configuration = minimalConfigurationBuilder
.tokenEndpointAuthenticationMethod("should-be-removed")
.tokenEndpointAuthenticationMethods(authMethods -> {
authMethods.clear();
authMethods.add("some-authentication-method");
})
.build();
assertThat(configuration.getTokenEndpointAuthenticationMethods()).containsExactly("some-authentication-method");
}
@Test
public void claimWhenNameIsNullThenThrowIllegalArgumentException() {
OidcProviderConfiguration.Builder builder = OidcProviderConfiguration.withClaims();
assertThatThrownBy(() -> builder.claim(null, "value"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name cannot be empty");
}
@Test
public void claimWhenValueIsNullThenThrowIllegalArgumentException() {
OidcProviderConfiguration.Builder builder = OidcProviderConfiguration.withClaims();
assertThatThrownBy(() -> builder.claim("claim-name", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("value cannot be null");
}
@Test
public void claimsWhenRemovingAClaimThenIsNotPresent() {
OidcProviderConfiguration configuration =
minimalConfigurationBuilder
.grantType("some-grant-type")
.claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED))
.build();
assertThat(configuration.getGrantTypes()).isNull();
}
@Test
public void claimsWhenAddingAClaimThenIsPresent() {
OidcProviderConfiguration configuration =
minimalConfigurationBuilder
.claims((claims) -> claims.put(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, "authorization_code"))
.build();
assertThat(configuration.getGrantTypes()).containsExactly("authorization_code");
}
private static URL url(String urlString) {
try {
return new URL(urlString);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("urlString must be a valid URL and valid URI");
}
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright 2020 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.oauth2.server.authorization.config;
import org.junit.Test;
import java.net.MalformedURLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link ProviderSettings}.
*
* @author Daniel Garnier-Moiroux
*/
public class ProviderSettingsTests {
@Test
public void constructorWhenDefaultThenDefaultsAreSetAndIssuerIsNotSet() {
ProviderSettings providerSettings = new ProviderSettings();
assertThat(providerSettings.issuer()).isNull();
assertThat(providerSettings.authorizationEndpoint()).isEqualTo("/oauth2/authorize");
assertThat(providerSettings.tokenEndpoint()).isEqualTo("/oauth2/token");
assertThat(providerSettings.jwkSetEndpoint()).isEqualTo("/oauth2/jwks");
assertThat(providerSettings.tokenRevocationEndpoint()).isEqualTo("/oauth2/revoke");
}
@Test
public void settingsWhenProvidedThenSet() throws MalformedURLException {
String authorizationEndpoint = "/my-endpoints/authorize";
String tokenEndpoint = "/my-endpoints/token";
String jwksEndpoint = "/my-endpoints/jwks";
String tokenRevocationEndpoint = "/my-endpoints/revoke";
String issuer = "https://example.com/9000";
ProviderSettings providerSettings = new ProviderSettings()
.issuer(issuer)
.authorizationEndpoint(authorizationEndpoint)
.tokenEndpoint(tokenEndpoint)
.jwkSetEndpoint(jwksEndpoint)
.tokenRevocationEndpoint(tokenRevocationEndpoint);
assertThat(providerSettings.issuer()).isEqualTo(issuer);
assertThat(providerSettings.authorizationEndpoint()).isEqualTo(authorizationEndpoint);
assertThat(providerSettings.tokenEndpoint()).isEqualTo(tokenEndpoint);
assertThat(providerSettings.jwkSetEndpoint()).isEqualTo(jwksEndpoint);
assertThat(providerSettings.tokenRevocationEndpoint()).isEqualTo(tokenRevocationEndpoint);
}
@Test
public void settingWhenCalledThenReturnTokenSettings() {
ProviderSettings providerSettings = new ProviderSettings()
.setting("name1", "value1")
.settings(settings -> settings.put("name2", "value2"));
assertThat(providerSettings.settings()).hasSize(6);
assertThat(providerSettings.<String>setting("name1")).isEqualTo("value1");
assertThat(providerSettings.<String>setting("name2")).isEqualTo("value2");
}
@Test
public void issuerWhenNullThenThrowsIllegalArgumentException() {
ProviderSettings settings = new ProviderSettings();
assertThatThrownBy(() -> settings.issuer(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issuer cannot be null");
}
@Test
public void authorizationEndpointWhenNullThenThrowsIllegalArgumentException() {
ProviderSettings settings = new ProviderSettings();
assertThatThrownBy(() -> settings.authorizationEndpoint(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizationEndpoint cannot be empty");
assertThatThrownBy(() -> settings.authorizationEndpoint(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizationEndpoint cannot be empty");
}
@Test
public void tokenEndpointWhenNullThenThrowsIllegalArgumentException() {
ProviderSettings settings = new ProviderSettings();
assertThatThrownBy(() -> settings.tokenEndpoint(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tokenEndpoint cannot be empty");
assertThatThrownBy(() -> settings.tokenEndpoint(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tokenEndpoint cannot be empty");
}
@Test
public void tokenRevocationEndpointWhenNullThenThrowsIllegalArgumentException() {
ProviderSettings settings = new ProviderSettings();
assertThatThrownBy(() -> settings.tokenRevocationEndpoint(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tokenRevocationEndpoint cannot be empty");
assertThatThrownBy(() -> settings.tokenRevocationEndpoint(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tokenRevocationEndpoint cannot be empty");
}
@Test
public void jwkSetEndpointWhenNullThenThrowsIllegalArgumentException() {
ProviderSettings settings = new ProviderSettings();
assertThatThrownBy(() -> settings.jwkSetEndpoint(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("jwkSetEndpoint cannot be empty");
assertThatThrownBy(() -> settings.jwkSetEndpoint(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("jwkSetEndpoint cannot be empty");
}
}

View File

@@ -0,0 +1,112 @@
/*
* Copyright 2020 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.oauth2.server.authorization.web;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link OidcProviderConfigurationEndpointFilter}.
*
* @author Daniel Garnier-Moiroux
*/
public class OidcProviderConfigurationEndpointFilterTests {
@Test
public void constructorWhenProviderSettingsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OidcProviderConfigurationEndpointFilter(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("providerSettings cannot be null");
}
@Test
public void doFilterWhenRequestDoesNotMatchThenNotProcessed() throws Exception {
OidcProviderConfigurationEndpointFilter filter = new OidcProviderConfigurationEndpointFilter(new ProviderSettings());
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenSuccessThenConfigurationResponse() throws Exception {
String authorizationEndpoint = "/my-endpoints/authorize";
String tokenEndpoint = "/my-endpoints/token";
String jwksEndpoint = "/my-endpoints/jwks";
ProviderSettings providerSettings = new ProviderSettings()
.issuer("https://example.com/issuer1")
.authorizationEndpoint(authorizationEndpoint)
.tokenEndpoint(tokenEndpoint)
.jwkSetEndpoint(jwksEndpoint);
OidcProviderConfigurationEndpointFilter filter = new OidcProviderConfigurationEndpointFilter(providerSettings);
MockHttpServletRequest request = new MockHttpServletRequest("GET", org.springframework.security.oauth2.server.authorization.web.OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI);
request.setServletPath(org.springframework.security.oauth2.server.authorization.web.OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
filter.doFilter(request, response, filterChain);
verifyNoInteractions(filterChain);
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
String providerConfigurationResponse = response.getContentAsString();
assertThat(providerConfigurationResponse).contains("\"issuer\":\"https://example.com/issuer1\"");
assertThat(providerConfigurationResponse).contains("\"authorization_endpoint\":\"https://example.com/issuer1/my-endpoints/authorize\"");
assertThat(providerConfigurationResponse).contains("\"token_endpoint\":\"https://example.com/issuer1/my-endpoints/token\"");
assertThat(providerConfigurationResponse).contains("\"jwks_uri\":\"https://example.com/issuer1/my-endpoints/jwks\"");
assertThat(providerConfigurationResponse).contains("\"scopes_supported\":[\"openid\"]");
assertThat(providerConfigurationResponse).contains("\"response_types_supported\":[\"code\"]");
assertThat(providerConfigurationResponse).contains("\"grant_types_supported\":[\"authorization_code\",\"client_credentials\"]");
assertThat(providerConfigurationResponse).contains("\"subject_types_supported\":[\"public\"]");
assertThat(providerConfigurationResponse).contains("\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\"]");
}
@Test
public void doFilterWhenProviderSettingsWithInvalidIssuerThenThrowIllegalArgumentException() {
ProviderSettings providerSettings = new ProviderSettings()
.issuer("https://this is an invalid URL");
OidcProviderConfigurationEndpointFilter filter = new OidcProviderConfigurationEndpointFilter(providerSettings);
MockHttpServletRequest request = new MockHttpServletRequest("GET", org.springframework.security.oauth2.server.authorization.web.OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI);
request.setServletPath(org.springframework.security.oauth2.server.authorization.web.OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
assertThatThrownBy(() -> filter.doFilter(request, response, filterChain))
.isInstanceOf(IllegalArgumentException.class);
}
}