repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java | /*
* Copyright 2002-2022 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.client.web.server;
import java.util.Map;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
* @since 5.1
*/
public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests {
private WebSessionOAuth2ServerAuthorizationRequestRepository repository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
// @formatter:off
private OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("https://example.com/oauth2/authorize")
.clientId("client-id")
.redirectUri("http://localhost/client-1")
.state("state")
.build();
// @formatter:on
private ServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/").queryParam(OAuth2ParameterNames.STATE, "state"));
@Test
public void loadAuthorizationRequestWhenNullExchangeThenIllegalArgumentException() {
this.exchange = null;
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.loadAuthorizationRequest(this.exchange));
}
@Test
public void loadAuthorizationRequestWhenNoSessionThenEmpty() {
// @formatter:off
StepVerifier.create(this.repository.loadAuthorizationRequest(this.exchange))
.verifyComplete();
// @formatter:on
assertSessionStartedIs(false);
}
@Test
public void loadAuthorizationRequestWhenSessionAndNoRequestThenEmpty() {
// @formatter:off
Mono<OAuth2AuthorizationRequest> setAttrThenLoad = this.exchange.getSession()
.map(WebSession::getAttributes)
.doOnNext((attrs) -> attrs.put("foo", "bar"))
.then(this.repository.loadAuthorizationRequest(this.exchange));
StepVerifier.create(setAttrThenLoad)
.verifyComplete();
// @formatter:on
}
@Test
public void loadAuthorizationRequestWhenNoStateParamThenEmpty() {
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
// @formatter:off
Mono<OAuth2AuthorizationRequest> saveAndLoad = this.repository
.saveAuthorizationRequest(this.authorizationRequest, this.exchange)
.then(this.repository.loadAuthorizationRequest(this.exchange));
StepVerifier.create(saveAndLoad)
.verifyComplete();
// @formatter:on
}
@Test
public void loadAuthorizationRequestWhenSavedThenAuthorizationRequest() {
// @formatter:off
Mono<OAuth2AuthorizationRequest> saveAndLoad = this.repository
.saveAuthorizationRequest(this.authorizationRequest, this.exchange)
.then(this.repository.loadAuthorizationRequest(this.exchange));
StepVerifier.create(saveAndLoad)
.expectNext(this.authorizationRequest)
.verifyComplete();
// @formatter:on
}
@Test
public void saveAuthorizationRequestWhenAuthorizationRequestNullThenThrowsIllegalArgumentException() {
this.authorizationRequest = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange));
assertSessionStartedIs(false);
}
@Test
public void saveAuthorizationRequestWhenExchangeNullThenThrowsIllegalArgumentException() {
this.exchange = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange));
}
@Test
public void removeAuthorizationRequestWhenExchangeNullThenThrowsIllegalArgumentException() {
this.exchange = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.removeAuthorizationRequest(this.exchange));
}
@Test
public void removeAuthorizationRequestWhenNotPresentThenThrowsIllegalArgumentException() {
StepVerifier.create(this.repository.removeAuthorizationRequest(this.exchange)).verifyComplete();
assertSessionStartedIs(false);
}
@Test
public void removeAuthorizationRequestWhenPresentThenFoundAndRemoved() {
// @formatter:off
Mono<OAuth2AuthorizationRequest> saveAndRemove = this.repository
.saveAuthorizationRequest(this.authorizationRequest, this.exchange)
.then(this.repository.removeAuthorizationRequest(this.exchange));
StepVerifier.create(saveAndRemove)
.expectNext(this.authorizationRequest)
.verifyComplete();
StepVerifier.create(this.exchange
.getSession()
.map(WebSession::getAttributes)
.map(Map::isEmpty)
)
.expectNext(true).verifyComplete();
// @formatter:on
}
// gh-5599
@Test
public void removeAuthorizationRequestWhenStateMissingThenNoErrors() {
// @formatter:off
MockServerHttpRequest otherState = MockServerHttpRequest.get("/")
.queryParam(OAuth2ParameterNames.STATE, "other")
.build();
ServerWebExchange otherStateExchange = this.exchange.mutate()
.request(otherState)
.build();
Mono<OAuth2AuthorizationRequest> saveAndRemove = this.repository
.saveAuthorizationRequest(this.authorizationRequest, this.exchange)
.then(this.repository.removeAuthorizationRequest(otherStateExchange));
StepVerifier.create(saveAndRemove)
.verifyComplete();
// @formatter:on
}
private void assertSessionStartedIs(boolean expected) {
// @formatter:off
Mono<Boolean> isStarted = this.exchange.getSession()
.map(WebSession::isStarted);
StepVerifier.create(isStarted)
.expectNext(expected)
.verifyComplete();
// @formatter:on
}
}
| 6,422 | 34.683333 | 134 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java | /*
* Copyright 2002-2018 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.client.web.server;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests {
private String registrationId = "registrationId";
private String principalName = "principalName";
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
private ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository;
private AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
@BeforeEach
public void setup() {
this.authorizedClientService = mock(ReactiveOAuth2AuthorizedClientService.class);
this.anonymousAuthorizedClientRepository = mock(ServerOAuth2AuthorizedClientRepository.class);
this.authorizedClientRepository = new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(
this.authorizedClientService);
this.authorizedClientRepository
.setAnonymousAuthorizedClientRepository(this.anonymousAuthorizedClientRepository);
}
@Test
public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null));
}
@Test
public void setAuthorizedClientRepositoryWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null));
}
@Test
public void loadAuthorizedClientWhenAuthenticatedPrincipalThenLoadFromService() {
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
Authentication authentication = this.createAuthenticatedPrincipal();
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.exchange)
.block();
verify(this.authorizedClientService).loadAuthorizedClient(this.registrationId, this.principalName);
}
@Test
public void loadAuthorizedClientWhenAnonymousPrincipalThenLoadFromAnonymousRepository() {
given(this.anonymousAuthorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.empty());
Authentication authentication = this.createAnonymousPrincipal();
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.exchange)
.block();
verify(this.anonymousAuthorizedClientRepository).loadAuthorizedClient(this.registrationId, authentication,
this.exchange);
}
@Test
public void saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService() {
given(this.authorizedClientService.saveAuthorizedClient(any(), any())).willReturn(Mono.empty());
Authentication authentication = this.createAuthenticatedPrincipal();
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.exchange).block();
verify(this.authorizedClientService).saveAuthorizedClient(authorizedClient, authentication);
}
@Test
public void saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository() {
given(this.anonymousAuthorizedClientRepository.saveAuthorizedClient(any(), any(), any()))
.willReturn(Mono.empty());
Authentication authentication = this.createAnonymousPrincipal();
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.exchange).block();
verify(this.anonymousAuthorizedClientRepository).saveAuthorizedClient(authorizedClient, authentication,
this.exchange);
}
@Test
public void removeAuthorizedClientWhenAuthenticatedPrincipalThenRemoveFromService() {
given(this.authorizedClientService.removeAuthorizedClient(any(), any())).willReturn(Mono.empty());
Authentication authentication = this.createAuthenticatedPrincipal();
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.exchange)
.block();
verify(this.authorizedClientService).removeAuthorizedClient(this.registrationId, this.principalName);
}
@Test
public void removeAuthorizedClientWhenAnonymousPrincipalThenRemoveFromAnonymousRepository() {
given(this.anonymousAuthorizedClientRepository.removeAuthorizedClient(any(), any(), any()))
.willReturn(Mono.empty());
Authentication authentication = this.createAnonymousPrincipal();
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.exchange)
.block();
verify(this.anonymousAuthorizedClientRepository).removeAuthorizedClient(this.registrationId, authentication,
this.exchange);
}
private Authentication createAuthenticatedPrincipal() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName, "password");
authentication.setAuthenticated(true);
return authentication;
}
private Authentication createAnonymousPrincipal() {
return new AnonymousAuthenticationToken("key-1234", "anonymousUser",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
}
}
| 6,974 | 45.5 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java | /*
* Copyright 2002-2022 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.client.web.server;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
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.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class DefaultServerOAuth2AuthorizationRequestResolverTests {
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private DefaultServerOAuth2AuthorizationRequestResolver resolver;
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
@BeforeEach
public void setup() {
this.resolver = new DefaultServerOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository);
}
@Test
public void setAuthorizationRequestCustomizerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null));
}
@Test
public void resolveWhenNotMatchThenNull() {
assertThat(resolve("/")).isNull();
}
@Test
public void resolveWhenClientRegistrationNotFoundMatchThenBadRequest() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
assertThatExceptionOfType(ResponseStatusException.class)
.isThrownBy(() -> resolve("/oauth2/authorization/not-found-id"))
.satisfies((ex) -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
public void resolveWhenClientRegistrationFoundThenWorks() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/not-found-id");
assertThat(request.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenForwardedHeadersClientRegistrationFoundThenWorks() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> httpRequest = MockServerHttpRequest
.get("/oauth2/authorization/id")
.header("X-Forwarded-Host", "evil.com");
// @formatter:on
ServerWebExchange exchange = MockServerWebExchange.from(httpRequest);
OAuth2AuthorizationRequest request = this.resolver.resolve(exchange).block();
assertThat(request.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenAuthorizationRequestWithValidPublicClientThenResolves() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration()
.clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build()));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
// gh-6548
@Test
public void resolveWhenAuthorizationRequestApplyPkceToConfidentialClientsThenApplied() {
ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration1.getRegistrationId())))
.willReturn(Mono.just(registration1));
ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration2.getRegistrationId())))
.willReturn(Mono.just(registration2));
this.resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/" + registration1.getRegistrationId());
assertPkceApplied(request, registration1);
request = resolve("/oauth2/authorization/" + registration2.getRegistrationId());
assertPkceApplied(request, registration2);
}
// gh-6548
@Test
public void resolveWhenAuthorizationRequestApplyPkceToSpecificConfidentialClientThenApplied() {
ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration1.getRegistrationId())))
.willReturn(Mono.just(registration1));
ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration2.getRegistrationId())))
.willReturn(Mono.just(registration2));
this.resolver.setAuthorizationRequestCustomizer((builder) -> {
builder.attributes((attrs) -> {
String registrationId = (String) attrs.get(OAuth2ParameterNames.REGISTRATION_ID);
if (registration1.getRegistrationId().equals(registrationId)) {
OAuth2AuthorizationRequestCustomizers.withPkce().accept(builder);
}
});
});
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/" + registration1.getRegistrationId());
assertPkceApplied(request, registration1);
request = resolve("/oauth2/authorization/" + registration2.getRegistrationId());
assertPkceNotApplied(request, registration2);
}
private void assertPkceApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.contains(entry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"));
assertThat(authorizationRequest.getAttributes()).containsKey(PkceParameterNames.CODE_VERIFIER);
assertThat((String) authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=/login/oauth2/code/" + clientRegistration.getRegistrationId() + "&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
private void assertPkceNotApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(PkceParameterNames.CODE_CHALLENGE_METHOD);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(PkceParameterNames.CODE_VERIFIER);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(OidcParameterNames.NONCE)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=openid&state=.*?&"
+ "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}");
}
// gh-7696
@Test
public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer(
(builder) -> builder.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE))
.attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).containsKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.authorizationRequestUri((uriBuilder) -> {
uriBuilder.queryParam("param1", "value1");
return uriBuilder.build();
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "param1=value1");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.parameters((params) -> {
params.put("appid", params.get("client_id"));
params.remove("client_id");
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&"
+ "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "appid=client-id");
}
private OAuth2AuthorizationRequest resolve(String path) {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path));
return this.resolver.resolve(exchange).block();
}
}
| 13,906 | 52.283525 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepositoryTests.java | /*
* Copyright 2002-2018 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.client.web.server;
import org.junit.jupiter.api.Test;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.web.server.WebSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
* @since 5.1
*/
public class WebSessionServerOAuth2AuthorizedClientRepositoryTests {
private WebSessionServerOAuth2AuthorizedClientRepository authorizedClientRepository = new WebSessionServerOAuth2AuthorizedClientRepository();
private MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
private ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();
private ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
private String registrationId1 = this.registration1.getRegistrationId();
private String registrationId2 = this.registration2.getRegistrationId();
private String principalName1 = "principalName-1";
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.exchange).block());
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, this.exchange).block();
}
@Test
public void loadAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null).block());
}
@Test
public void loadAuthorizedClientWhenClientRegistrationNotFoundThenReturnNull() {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository
.loadAuthorizedClient("registration-not-found", null, this.exchange).block();
assertThat(authorizedClient).isNull();
}
@Test
public void loadAuthorizedClientWhenSavedThenReturnAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.exchange).block();
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.exchange).block();
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.exchange).block());
}
@Test
public void saveAuthorizedClientWhenAuthenticationIsNullThenExceptionNotThrown() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.exchange).block();
}
@Test
public void saveAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, null).block());
}
@Test
public void saveAuthorizedClientWhenSavedThenSavedToSession() {
OAuth2AuthorizedClient expected = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(expected, null, this.exchange).block();
OAuth2AuthorizedClient result = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.exchange).block();
assertThat(result).isEqualTo(expected);
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.exchange));
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.exchange);
}
@Test
public void removeAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, null));
}
@Test
public void removeAuthorizedClientWhenNotSavedThenSessionNotCreated() {
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.exchange);
assertThat(this.exchange.getSession().block().isStarted()).isFalse();
}
@Test
public void removeAuthorizedClientWhenClient1SavedAndClient2RemovedThenClient1NotRemoved() {
OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.exchange).block();
// Remove registrationId2 (never added so is not removed either)
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.exchange);
OAuth2AuthorizedClient loadedAuthorizedClient1 = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.exchange).block();
assertThat(loadedAuthorizedClient1).isNotNull();
assertThat(loadedAuthorizedClient1).isSameAs(authorizedClient1);
}
@Test
public void removeAuthorizedClientWhenSavedThenRemoved() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.exchange).block();
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.exchange).block();
assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.exchange).block();
loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.exchange).block();
assertThat(loadedAuthorizedClient).isNull();
}
@Test
public void removeAuthorizedClientWhenSavedThenRemovedFromSession() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.exchange).block();
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.exchange).block();
assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.exchange).block();
WebSession session = this.exchange.getSession().block();
assertThat(session).isNotNull();
assertThat(session.getAttributes()).isEmpty();
}
@Test
public void removeAuthorizedClientWhenClient1Client2SavedAndClient1RemovedThenClient2NotRemoved() {
OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.exchange).block();
OAuth2AuthorizedClient authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient2, null, this.exchange).block();
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.exchange).block();
OAuth2AuthorizedClient loadedAuthorizedClient2 = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.exchange).block();
assertThat(loadedAuthorizedClient2).isNotNull();
assertThat(loadedAuthorizedClient2).isSameAs(authorizedClient2);
}
}
| 9,677 | 47.878788 | 142 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java | /*
* Copyright 2002-2019 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.client.web.server;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.test.web.reactive.server.FluxExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.server.handler.FilteringWebHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2AuthorizationRequestRedirectWebFilterTests {
@Mock
private ReactiveClientRegistrationRepository clientRepository;
@Mock
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authzRequestRepository;
@Mock
private ServerRequestCache requestCache;
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private OAuth2AuthorizationRequestRedirectWebFilter filter;
private WebTestClient client;
@BeforeEach
public void setup() {
this.filter = new OAuth2AuthorizationRequestRedirectWebFilter(this.clientRepository);
this.filter.setAuthorizationRequestRepository(this.authzRequestRepository);
FilteringWebHandler webHandler = new FilteringWebHandler((e) -> e.getResponse().setComplete(),
Arrays.asList(this.filter));
this.client = WebTestClient.bindToWebHandler(webHandler).build();
}
@Test
public void constructorWhenClientRegistrationRepositoryNullThenIllegalArgumentException() {
this.clientRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationRequestRedirectWebFilter(this.clientRepository));
}
@Test
public void setterWhenAuthorizationRedirectStrategyNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRedirectStrategy(null));
}
@Test
public void filterWhenDoesNotMatchThenClientRegistrationRepositoryNotSubscribed() {
// @formatter:off
this.client.get()
.exchange()
.expectStatus().isOk();
// @formatter:on
verifyNoInteractions(this.clientRepository, this.authzRequestRepository);
}
@Test
public void filterWhenDoesMatchThenClientRegistrationRepositoryNotSubscribed() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
// @formatter:off
FluxExchangeResult<String> result = this.client.get()
.uri("https://example.com/oauth2/authorization/registration-id")
.exchange()
.expectStatus().is3xxRedirection()
.returnResult(String.class);
// @formatter:on
result.assertWithDiagnostics(() -> {
URI location = result.getResponseHeaders().getLocation();
assertThat(location).hasScheme("https").hasHost("example.com").hasPath("/login/oauth/authorize")
.hasParameter("response_type", "code").hasParameter("client_id", "client-id")
.hasParameter("scope", "read:user").hasParameter("state")
.hasParameter("redirect_uri", "https://example.com/login/oauth2/code/registration-id");
});
verify(this.authzRequestRepository).saveAuthorizationRequest(any(), any());
}
// gh-5520
@Test
public void filterWhenDoesMatchThenResolveRedirectUriExpandedExcludesQueryString() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
// @formatter:off
FluxExchangeResult<String> result = this.client.get()
.uri("https://example.com/oauth2/authorization/registration-id?foo=bar").exchange().expectStatus()
.is3xxRedirection().returnResult(String.class);
result.assertWithDiagnostics(() -> {
URI location = result.getResponseHeaders().getLocation();
assertThat(location)
.hasScheme("https")
.hasHost("example.com")
.hasPath("/login/oauth/authorize")
.hasParameter("response_type", "code")
.hasParameter("client_id", "client-id")
.hasParameter("scope", "read:user")
.hasParameter("state")
.hasParameter("redirect_uri", "https://example.com/login/oauth2/code/registration-id");
});
// @formatter:on
}
@Test
public void filterWhenExceptionThenRedirected() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
FilteringWebHandler webHandler = new FilteringWebHandler(
(e) -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
Arrays.asList(this.filter));
// @formatter:off
this.client = WebTestClient.bindToWebHandler(webHandler)
.build();
FluxExchangeResult<String> result = this.client.get()
.uri("https://example.com/foo")
.exchange()
.expectStatus().is3xxRedirection()
.returnResult(String.class);
// @formatter:on
}
@Test
public void filterWhenExceptionThenSaveRequestSessionAttribute() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
this.filter.setRequestCache(this.requestCache);
given(this.requestCache.saveRequest(any())).willReturn(Mono.empty());
FilteringWebHandler webHandler = new FilteringWebHandler(
(e) -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
Arrays.asList(this.filter));
// @formatter:off
this.client = WebTestClient.bindToWebHandler(webHandler)
.build();
this.client.get()
.uri("https://example.com/foo")
.exchange()
.expectStatus().is3xxRedirection()
.returnResult(String.class);
// @formatter:on
verify(this.requestCache).saveRequest(any());
}
@Test
public void filterWhenPathMatchesThenRequestSessionAttributeNotSaved() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
this.filter.setRequestCache(this.requestCache);
// @formatter:off
this.client.get()
.uri("https://example.com/oauth2/authorization/registration-id")
.exchange()
.expectStatus().is3xxRedirection()
.returnResult(String.class);
// @formatter:on
verifyNoInteractions(this.requestCache);
}
@Test
public void filterWhenCustomRedirectStrategySetThenRedirectUriInResponseBody() {
given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId()))
.willReturn(Mono.just(this.registration));
given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
ServerRedirectStrategy customRedirectStrategy = (exchange, location) -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
DataBuffer buffer = exchange.getResponse().bufferFactory()
.wrap(location.toASCIIString().getBytes(StandardCharsets.UTF_8));
return exchange.getResponse().writeWith(Flux.just(buffer));
};
this.filter.setAuthorizationRedirectStrategy(customRedirectStrategy);
this.filter.setRequestCache(this.requestCache);
FluxExchangeResult<String> result = this.client.get()
.uri("https://example.com/oauth2/authorization/registration-id").exchange().expectHeader()
.contentType(MediaType.TEXT_PLAIN).expectStatus().isOk().returnResult(String.class);
// @formatter:off
StepVerifier.create(result.getResponseBody())
.assertNext((uri) -> {
URI location = URI.create(uri);
assertThat(location)
.hasScheme("https")
.hasHost("example.com")
.hasPath("/login/oauth/authorize")
.hasParameter("response_type", "code")
.hasParameter("client_id", "client-id")
.hasParameter("scope", "read:user")
.hasParameter("state")
.hasParameter("redirect_uri", "https://example.com/login/oauth2/code/registration-id");
})
.verifyComplete();
// @formatter:on
verifyNoInteractions(this.requestCache);
}
}
| 10,452 | 40.153543 | 108 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java | /*
* Copyright 2002-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.client.web.server;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests {
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@Mock
private ServerAuthorizationRequestRepository authorizationRequestRepository;
private String clientRegistrationId = "github";
// @formatter:off
private ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(this.clientRegistrationId)
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://github.com/login/oauth/authorize")
.tokenUri("https://github.com/login/oauth/access_token")
.userInfoUri("https://api.github.com/user")
.userNameAttributeName("id")
.clientName("GitHub")
.clientId("clientId")
.clientSecret("clientSecret")
.build();
// @formatter:on
// @formatter:off
private OAuth2AuthorizationRequest.Builder authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("https://example.com/oauth2/authorize")
.clientId("client-id")
.redirectUri("http://localhost/client-1")
.state("state")
.attributes(Collections.singletonMap(OAuth2ParameterNames.REGISTRATION_ID, this.clientRegistrationId));
// @formatter:on
private final MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/");
private ServerOAuth2AuthorizationCodeAuthenticationTokenConverter converter;
@BeforeEach
public void setup() {
this.converter = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
this.clientRegistrationRepository);
this.converter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
}
@Test
public void applyWhenAuthorizationRequestEmptyThenOAuth2AuthorizationException() {
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.empty());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter());
}
@Test
public void applyWhenAttributesMissingThenOAuth2AuthorizationException() {
this.authorizationRequest.attributes(Map::clear);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(this.authorizationRequest.build()));
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter())
.withMessageContaining(
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
}
@Test
public void applyWhenClientRegistrationMissingThenOAuth2AuthorizationException() {
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter())
.withMessageContaining(
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
}
@Test
public void applyWhenCodeParameterNotFoundThenErrorCode() {
this.request.queryParam(OAuth2ParameterNames.ERROR, "error");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(this.clientRegistration));
assertThat(applyConverter().getAuthorizationExchange().getAuthorizationResponse().getError().getErrorCode())
.isEqualTo("error");
}
@Test
public void applyWhenCodeParameterFoundThenCode() {
this.request.queryParam(OAuth2ParameterNames.CODE, "code");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizationCodeAuthenticationToken result = applyConverter();
OAuth2AuthorizationResponse exchange = result.getAuthorizationExchange().getAuthorizationResponse();
assertThat(exchange.getError()).isNull();
assertThat(exchange.getCode()).isEqualTo("code");
}
private OAuth2AuthorizationCodeAuthenticationToken applyConverter() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
return (OAuth2AuthorizationCodeAuthenticationToken) this.converter.convert(exchange).block();
}
}
| 6,854 | 43.803922 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java | /*
* Copyright 2002-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.client.web.server;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.authentication.TestOAuth2AuthorizationCodeAuthenticationTokens;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.handler.DefaultWebFilterChain;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* @author Rob Winch
* @author Parikshit Dutta
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2AuthorizationCodeGrantWebFilterTests {
private OAuth2AuthorizationCodeGrantWebFilter filter;
@Mock
private ReactiveAuthenticationManager authenticationManager;
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@Mock
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
@Mock
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
@BeforeEach
public void setup() {
this.filter = new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository);
this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
}
@Test
public void constructorWhenAuthenticationManagerNullThenIllegalArgumentException() {
this.authenticationManager = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void constructorWhenClientRegistrationRepositoryNullThenIllegalArgumentException() {
this.clientRegistrationRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void constructorWhenAuthorizedClientRepositoryNullThenIllegalArgumentException() {
this.authorizedClientRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null));
}
@Test
public void filterWhenNotMatchThenAuthenticationManagerNotCalled() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
}
@Test
public void filterWhenMatchThenAuthorizedClientSaved() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(AnonymousAuthenticationToken.class),
any());
}
// gh-7966
@Test
public void filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
// 1) redirect_uri with query parameters
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback", parameters);
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(1)).authenticate(any());
// 2) redirect_uri with query parameters AND authorization response additional
// parameters
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(2)).authenticate(any());
}
// gh-7966
@Test
public void filterWhenAuthorizationRequestRedirectUriParametersNotMatchThenNotProcessed() {
String requestUri = "/authorization/callback";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
// 1) Parameter value
Map<String, String> parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.put("param2", "value8");
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(
createAuthorizationRequest(requestUri, parametersNotMatch));
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
// 2) Parameter order
parametersNotMatch = new LinkedHashMap<>();
parametersNotMatch.put("param2", "value2");
parametersNotMatch.put("param1", "value1");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
// 3) Parameter missing
parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.remove("param2");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
}
@Test
public void filterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
ServerRequestCache requestCache = mock(ServerRequestCache.class);
given(requestCache.getRedirectUri(any(ServerWebExchange.class)))
.willReturn(Mono.just(URI.create("/saved-request")));
this.filter.setRequestCache(requestCache);
this.filter.filter(exchange, chain).block();
verify(requestCache).getRedirectUri(exchange);
assertThat(exchange.getResponse().getHeaders().getLocation().toString()).isEqualTo("/saved-request");
}
// gh-8609
@Test
public void filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.filter.filter(exchange, chain).block())
.satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode")
.isEqualTo("client_registration_not_found"));
verifyNoInteractions(this.authenticationManager);
}
// gh-8609
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.filter.filter(exchange, chain).block())
.satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
private static OAuth2AuthorizationRequest createOAuth2AuthorizationRequest(
MockServerHttpRequest authorizationRequest, ClientRegistration registration) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId());
// @formatter:off
return TestOAuth2AuthorizationRequests.request()
.attributes(attributes)
.redirectUri(authorizationRequest.getURI().toString())
.build();
// @formatter:on
}
private static MockServerHttpRequest createAuthorizationRequest(String requestUri) {
return createAuthorizationRequest(requestUri, new LinkedHashMap<>());
}
private static MockServerHttpRequest createAuthorizationRequest(String requestUri, Map<String, String> parameters) {
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get(requestUri);
if (!CollectionUtils.isEmpty(parameters)) {
parameters.forEach(builder::queryParam);
}
return builder.build();
}
private static MockServerHttpRequest createAuthorizationResponse(MockServerHttpRequest authorizationRequest) {
return createAuthorizationResponse(authorizationRequest, new LinkedHashMap<>());
}
private static MockServerHttpRequest createAuthorizationResponse(MockServerHttpRequest authorizationRequest,
Map<String, String> additionalParameters) {
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest
.get(authorizationRequest.getURI().toString());
builder.queryParam(OAuth2ParameterNames.CODE, "code");
builder.queryParam(OAuth2ParameterNames.STATE, "state");
additionalParameters.forEach(builder::queryParam);
builder.cookies(authorizationRequest.getCookies());
return builder.build();
}
}
| 18,036 | 52.05 | 125 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java | /*
* Copyright 2002-2018 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.client.web.server.authentication;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2LoginAuthenticationWebFilterTests {
@Mock
private ReactiveAuthenticationManager authenticationManager;
@Mock
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private OAuth2LoginAuthenticationWebFilter filter;
private WebFilterExchange webFilterExchange;
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
private OAuth2AuthorizationResponse.Builder authorizationResponseBldr = OAuth2AuthorizationResponse.success("code")
.state("state");
@BeforeEach
public void setup() {
this.filter = new OAuth2LoginAuthenticationWebFilter(this.authenticationManager,
this.authorizedClientRepository);
this.webFilterExchange = new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/")),
new DefaultWebFilterChain((exchange) -> exchange.getResponse().setComplete(), Collections.emptyList()));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
}
@Test
public void onAuthenticationSuccessWhenOAuth2LoginAuthenticationTokenThenSavesAuthorizedClient() {
this.filter.onAuthenticationSuccess(loginToken(), this.webFilterExchange).block();
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(), any());
}
private OAuth2LoginAuthenticationToken loginToken() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token",
Instant.now(), Instant.now().plus(Duration.ofDays(1)), Collections.singleton("user"));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
ClientRegistration clientRegistration = this.registration.build();
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.state("state")
.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails()
.getAuthorizationUri())
.redirectUri(clientRegistration.getRedirectUri())
.scopes(clientRegistration.getScopes())
.build();
OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr
.redirectUri(clientRegistration.getRedirectUri())
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2LoginAuthenticationToken(clientRegistration, authorizationExchange, user,
user.getAuthorities(), accessToken);
}
}
| 5,052 | 43.716814 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/aot/hint/OAuth2ClientRuntimeHintsTests.java | /*
* Copyright 2002-2022 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.client.aot.hint;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OAuth2ClientRuntimeHints}
*/
class OAuth2ClientRuntimeHintsTests {
private final RuntimeHints hints = new RuntimeHints();
@BeforeEach
void setup() {
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class)
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
}
@ParameterizedTest
@MethodSource("getOAuth2ClientSchemaFiles")
void oauth2ClientSchemaFilesHasHints(String schemaFile) {
assertThat(RuntimeHintsPredicates.resource().forResource(schemaFile)).accepts(this.hints);
}
private static Stream<String> getOAuth2ClientSchemaFiles() {
return Stream.of("org/springframework/security/oauth2/client/oauth2-client-schema.sql",
"org/springframework/security/oauth2/client/oauth2-client-schema-postgres.sql");
}
}
| 2,075 | 34.793103 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java | /*
* Copyright 2002-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.client.jackson2;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthorizationRequestMixin}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationRequestMixinTests {
private ObjectMapper mapper;
private OAuth2AuthorizationRequest.Builder authorizationRequestBuilder;
@BeforeEach
public void setup() {
ClassLoader loader = getClass().getClassLoader();
this.mapper = new ObjectMapper();
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
Map<String, Object> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
// @formatter:off
this.authorizationRequestBuilder = TestOAuth2AuthorizationRequests.request()
.scope("read", "write")
.additionalParameters(additionalParameters);
// @formatter:on
}
@Test
public void serializeWhenMixinRegisteredThenSerializes() throws Exception {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build();
String expectedJson = asJson(authorizationRequest);
String json = this.mapper.writeValueAsString(authorizationRequest);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception {
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder
.scopes(null)
.state(null)
.additionalParameters(Map::clear)
.attributes(Map::clear)
.build();
// @formatter:on
String expectedJson = asJson(authorizationRequest);
String json = this.mapper.writeValueAsString(authorizationRequest);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
String json = asJson(this.authorizationRequestBuilder.build());
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizationRequest.class));
}
@Test
public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception {
OAuth2AuthorizationRequest expectedAuthorizationRequest = this.authorizationRequestBuilder.build();
String json = asJson(expectedAuthorizationRequest);
OAuth2AuthorizationRequest authorizationRequest = this.mapper.readValue(json, OAuth2AuthorizationRequest.class);
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(expectedAuthorizationRequest.getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(expectedAuthorizationRequest.getGrantType());
assertThat(authorizationRequest.getResponseType()).isEqualTo(expectedAuthorizationRequest.getResponseType());
assertThat(authorizationRequest.getClientId()).isEqualTo(expectedAuthorizationRequest.getClientId());
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedAuthorizationRequest.getRedirectUri());
assertThat(authorizationRequest.getScopes()).isEqualTo(expectedAuthorizationRequest.getScopes());
assertThat(authorizationRequest.getState()).isEqualTo(expectedAuthorizationRequest.getState());
assertThat(authorizationRequest.getAdditionalParameters())
.containsExactlyEntriesOf(expectedAuthorizationRequest.getAdditionalParameters());
assertThat(authorizationRequest.getAuthorizationRequestUri())
.isEqualTo(expectedAuthorizationRequest.getAuthorizationRequestUri());
assertThat(authorizationRequest.getAttributes())
.containsExactlyEntriesOf(expectedAuthorizationRequest.getAttributes());
}
@Test
public void deserializeWhenRequiredAttributesOnlyThenDeserializes() throws Exception {
// @formatter:off
OAuth2AuthorizationRequest expectedAuthorizationRequest = this.authorizationRequestBuilder.scopes(null)
.state(null)
.additionalParameters(Map::clear)
.attributes(Map::clear)
.build();
// @formatter:on
String json = asJson(expectedAuthorizationRequest);
OAuth2AuthorizationRequest authorizationRequest = this.mapper.readValue(json, OAuth2AuthorizationRequest.class);
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(expectedAuthorizationRequest.getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(expectedAuthorizationRequest.getGrantType());
assertThat(authorizationRequest.getResponseType()).isEqualTo(expectedAuthorizationRequest.getResponseType());
assertThat(authorizationRequest.getClientId()).isEqualTo(expectedAuthorizationRequest.getClientId());
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedAuthorizationRequest.getRedirectUri());
assertThat(authorizationRequest.getScopes()).isEmpty();
assertThat(authorizationRequest.getState()).isNull();
assertThat(authorizationRequest.getAdditionalParameters()).isEmpty();
assertThat(authorizationRequest.getAuthorizationRequestUri())
.isEqualTo(expectedAuthorizationRequest.getAuthorizationRequestUri());
assertThat(authorizationRequest.getAttributes()).isEmpty();
}
@Test
public void deserializeWhenInvalidAuthorizationGrantTypeThenThrowJsonParseException() {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build();
String json = asJson(authorizationRequest).replace("authorization_code", "client_credentials");
assertThatExceptionOfType(JsonParseException.class)
.isThrownBy(() -> this.mapper.readValue(json, OAuth2AuthorizationRequest.class))
.withMessageContaining("Invalid authorizationGrantType");
}
private static String asJson(OAuth2AuthorizationRequest authorizationRequest) {
String scopes = "";
if (!CollectionUtils.isEmpty(authorizationRequest.getScopes())) {
scopes = StringUtils.collectionToDelimitedString(authorizationRequest.getScopes(), ",", "\"", "\"");
}
String additionalParameters = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
if (!CollectionUtils.isEmpty(authorizationRequest.getAdditionalParameters())) {
additionalParameters += "," + authorizationRequest.getAdditionalParameters().keySet().stream().map(
(key) -> "\"" + key + "\": \"" + authorizationRequest.getAdditionalParameters().get(key) + "\"")
.collect(Collectors.joining(","));
}
String attributes = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
if (!CollectionUtils.isEmpty(authorizationRequest.getAttributes())) {
attributes += "," + authorizationRequest.getAttributes().keySet().stream()
.map((key) -> "\"" + key + "\": \"" + authorizationRequest.getAttributes().get(key) + "\"")
.collect(Collectors.joining(","));
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest\",\n" +
" \"authorizationUri\": \"" + authorizationRequest.getAuthorizationUri() + "\",\n" +
" \"authorizationGrantType\": {\n" +
" \"value\": \"" + authorizationRequest.getGrantType().getValue() + "\"\n" +
" },\n" +
" \"responseType\": {\n" +
" \"value\": \"" + authorizationRequest.getResponseType().getValue() + "\"\n" +
" },\n" +
" \"clientId\": \"" + authorizationRequest.getClientId() + "\",\n" +
" \"redirectUri\": \"" + authorizationRequest.getRedirectUri() + "\",\n" +
" \"scopes\": [\n" +
" \"java.util.Collections$UnmodifiableSet\",\n" +
" [" + scopes + "]\n" +
" ],\n" +
" \"state\": " + ((authorizationRequest.getState() != null) ? "\"" + authorizationRequest.getState() + "\"" : "null") + ",\n" +
" \"additionalParameters\": {\n" +
" " + additionalParameters + "\n" +
" },\n" +
" \"authorizationRequestUri\": \"" + authorizationRequest.getAuthorizationRequestUri() + "\",\n" +
" \"attributes\": {\n" +
" " + attributes + "\n" +
" }\n" +
"}";
// @formatter:on
}
}
| 9,312 | 46.515306 | 132 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java | /*
* Copyright 2002-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.client.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthenticationExceptionMixin}.
*
* @author Dennis Neufeld
* @since 5.3.4
*/
public class OAuth2AuthenticationExceptionMixinTests {
private ObjectMapper mapper;
@BeforeEach
public void setup() {
ClassLoader loader = getClass().getClassLoader();
this.mapper = new ObjectMapper();
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
}
@Test
public void serializeWhenMixinRegisteredThenSerializes() throws Exception {
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(
new OAuth2Error("[authorization_request_not_found]", "Authorization Request Not Found", "/foo/bar"),
"Authorization Request Not Found");
String serializedJson = this.mapper.writeValueAsString(exception);
String expected = asJson(exception);
JSONAssert.assertEquals(expected, serializedJson, true);
}
@Test
public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception {
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(
new OAuth2Error("[authorization_request_not_found]"));
String serializedJson = this.mapper.writeValueAsString(exception);
String expected = asJson(exception);
JSONAssert.assertEquals(expected, serializedJson, true);
}
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
String json = asJson(new OAuth2AuthenticationException(new OAuth2Error("[authorization_request_not_found]")));
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationException.class));
}
@Test
public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception {
OAuth2AuthenticationException expected = new OAuth2AuthenticationException(
new OAuth2Error("[authorization_request_not_found]", "Authorization Request Not Found", "/foo/bar"),
"Authorization Request Not Found");
OAuth2AuthenticationException exception = this.mapper.readValue(asJson(expected),
OAuth2AuthenticationException.class);
assertThat(exception).isNotNull();
assertThat(exception.getCause()).isNull();
assertThat(exception.getMessage()).isEqualTo(expected.getMessage());
OAuth2Error oauth2Error = exception.getError();
assertThat(oauth2Error).isNotNull();
assertThat(oauth2Error.getErrorCode()).isEqualTo(expected.getError().getErrorCode());
assertThat(oauth2Error.getDescription()).isEqualTo(expected.getError().getDescription());
assertThat(oauth2Error.getUri()).isEqualTo(expected.getError().getUri());
}
@Test
public void deserializeWhenRequiredAttributesOnlyThenDeserializes() throws Exception {
OAuth2AuthenticationException expected = new OAuth2AuthenticationException(
new OAuth2Error("[authorization_request_not_found]"));
OAuth2AuthenticationException exception = this.mapper.readValue(asJson(expected),
OAuth2AuthenticationException.class);
assertThat(exception).isNotNull();
assertThat(exception.getCause()).isNull();
assertThat(exception.getMessage()).isNull();
OAuth2Error oauth2Error = exception.getError();
assertThat(oauth2Error).isNotNull();
assertThat(oauth2Error.getErrorCode()).isEqualTo(expected.getError().getErrorCode());
assertThat(oauth2Error.getDescription()).isNull();
assertThat(oauth2Error.getUri()).isNull();
}
private String asJson(OAuth2AuthenticationException exception) {
OAuth2Error error = exception.getError();
// @formatter:off
return "\n{"
+ "\n \"@class\": \"org.springframework.security.oauth2.core.OAuth2AuthenticationException\","
+ "\n \"error\":"
+ "\n {"
+ "\n \"@class\":\"org.springframework.security.oauth2.core.OAuth2Error\","
+ "\n \"errorCode\":\"" + error.getErrorCode() + "\","
+ "\n \"description\":" + jsonStringOrNull(error.getDescription()) + ","
+ "\n \"uri\":" + jsonStringOrNull(error.getUri())
+ "\n },"
+ "\n \"detailMessage\":" + jsonStringOrNull(exception.getMessage())
+ "\n}";
// @formatter:on
}
private String jsonStringOrNull(String input) {
return (input != null) ? "\"" + input + "\"" : "null";
}
}
| 5,410 | 40.623077 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java | /*
* Copyright 2002-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.oauth2.client.jackson2;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.DecimalUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthorizedClientMixin}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizedClientMixinTests {
private ObjectMapper mapper;
private ClientRegistration.Builder clientRegistrationBuilder;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
private String principalName;
@BeforeEach
public void setup() {
ClassLoader loader = getClass().getClassLoader();
this.mapper = new ObjectMapper();
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
Map<String, Object> providerConfigurationMetadata = new LinkedHashMap<>();
providerConfigurationMetadata.put("config1", "value1");
providerConfigurationMetadata.put("config2", "value2");
// @formatter:off
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration()
.authorizationGrantType(new AuthorizationGrantType("custom-grant"))
.scope("read", "write")
.providerConfigurationMetadata(providerConfigurationMetadata);
// @formatter:on
this.accessToken = TestOAuth2AccessTokens.scopes("read", "write");
this.refreshToken = TestOAuth2RefreshTokens.refreshToken();
this.principalName = "principal-name";
}
@Test
public void serializeWhenMixinRegisteredThenSerializes() throws Exception {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principalName, this.accessToken, this.refreshToken);
String expectedJson = asJson(authorizedClient);
String json = this.mapper.writeValueAsString(authorizedClient);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.clientSecret(null)
.clientName(null)
.userInfoUri(null)
.userNameAttributeName(null)
.jwkSetUri(null)
.issuerUri(null)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.principalName,
TestOAuth2AccessTokens.noScopes());
String expectedJson = asJson(authorizedClient);
String json = this.mapper.writeValueAsString(authorizedClient);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principalName, this.accessToken);
String json = asJson(authorizedClient);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizedClient.class));
}
@Test
public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception {
ClientRegistration expectedClientRegistration = this.clientRegistrationBuilder.build();
OAuth2AccessToken expectedAccessToken = this.accessToken;
OAuth2RefreshToken expectedRefreshToken = this.refreshToken;
OAuth2AuthorizedClient expectedAuthorizedClient = new OAuth2AuthorizedClient(expectedClientRegistration,
this.principalName, expectedAccessToken, expectedRefreshToken);
String json = asJson(expectedAuthorizedClient);
OAuth2AuthorizedClient authorizedClient = this.mapper.readValue(json, OAuth2AuthorizedClient.class);
ClientRegistration clientRegistration = authorizedClient.getClientRegistration();
assertThat(clientRegistration.getRegistrationId()).isEqualTo(expectedClientRegistration.getRegistrationId());
assertThat(clientRegistration.getClientId()).isEqualTo(expectedClientRegistration.getClientId());
assertThat(clientRegistration.getClientSecret()).isEqualTo(expectedClientRegistration.getClientSecret());
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(expectedClientRegistration.getClientAuthenticationMethod());
assertThat(clientRegistration.getAuthorizationGrantType())
.isEqualTo(expectedClientRegistration.getAuthorizationGrantType());
assertThat(clientRegistration.getRedirectUri()).isEqualTo(expectedClientRegistration.getRedirectUri());
assertThat(clientRegistration.getScopes()).isEqualTo(expectedClientRegistration.getScopes());
assertThat(clientRegistration.getProviderDetails().getAuthorizationUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(clientRegistration.getProviderDetails().getTokenUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getTokenUri());
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getUserInfoEndpoint().getUri());
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod()).isEqualTo(
expectedClientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod());
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).isEqualTo(
expectedClientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName());
assertThat(clientRegistration.getProviderDetails().getJwkSetUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getJwkSetUri());
assertThat(clientRegistration.getProviderDetails().getIssuerUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getIssuerUri());
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata())
.containsExactlyEntriesOf(clientRegistration.getProviderDetails().getConfigurationMetadata());
assertThat(clientRegistration.getClientName()).isEqualTo(expectedClientRegistration.getClientName());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expectedAuthorizedClient.getPrincipalName());
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
assertThat(accessToken.getTokenType()).isEqualTo(expectedAccessToken.getTokenType());
assertThat(accessToken.getScopes()).isEqualTo(expectedAccessToken.getScopes());
assertThat(accessToken.getTokenValue()).isEqualTo(expectedAccessToken.getTokenValue());
assertThat(accessToken.getIssuedAt()).isEqualTo(expectedAccessToken.getIssuedAt());
assertThat(accessToken.getExpiresAt()).isEqualTo(expectedAccessToken.getExpiresAt());
OAuth2RefreshToken refreshToken = authorizedClient.getRefreshToken();
assertThat(refreshToken.getTokenValue()).isEqualTo(expectedRefreshToken.getTokenValue());
assertThat(refreshToken.getIssuedAt()).isEqualTo(expectedRefreshToken.getIssuedAt());
assertThat(refreshToken.getExpiresAt()).isEqualTo(expectedRefreshToken.getExpiresAt());
}
@Test
public void deserializeWhenRequiredAttributesOnlyThenDeserializes() throws Exception {
// @formatter:off
ClientRegistration expectedClientRegistration = TestClientRegistrations.clientRegistration()
.clientSecret(null)
.clientName(null)
.userInfoUri(null)
.userNameAttributeName(null)
.jwkSetUri(null)
.issuerUri(null)
.build();
// @formatter:on
OAuth2AccessToken expectedAccessToken = TestOAuth2AccessTokens.noScopes();
OAuth2AuthorizedClient expectedAuthorizedClient = new OAuth2AuthorizedClient(expectedClientRegistration,
this.principalName, expectedAccessToken);
String json = asJson(expectedAuthorizedClient);
OAuth2AuthorizedClient authorizedClient = this.mapper.readValue(json, OAuth2AuthorizedClient.class);
ClientRegistration clientRegistration = authorizedClient.getClientRegistration();
assertThat(clientRegistration.getRegistrationId()).isEqualTo(expectedClientRegistration.getRegistrationId());
assertThat(clientRegistration.getClientId()).isEqualTo(expectedClientRegistration.getClientId());
assertThat(clientRegistration.getClientSecret()).isEmpty();
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(expectedClientRegistration.getClientAuthenticationMethod());
assertThat(clientRegistration.getAuthorizationGrantType())
.isEqualTo(expectedClientRegistration.getAuthorizationGrantType());
assertThat(clientRegistration.getRedirectUri()).isEqualTo(expectedClientRegistration.getRedirectUri());
assertThat(clientRegistration.getScopes()).isEqualTo(expectedClientRegistration.getScopes());
assertThat(clientRegistration.getProviderDetails().getAuthorizationUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(clientRegistration.getProviderDetails().getTokenUri())
.isEqualTo(expectedClientRegistration.getProviderDetails().getTokenUri());
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()).isNull();
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod()).isEqualTo(
expectedClientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod());
assertThat(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).isNull();
assertThat(clientRegistration.getProviderDetails().getJwkSetUri()).isNull();
assertThat(clientRegistration.getProviderDetails().getIssuerUri()).isNull();
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).isEmpty();
assertThat(clientRegistration.getClientName()).isEqualTo(clientRegistration.getRegistrationId());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expectedAuthorizedClient.getPrincipalName());
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
assertThat(accessToken.getTokenType()).isEqualTo(expectedAccessToken.getTokenType());
assertThat(accessToken.getScopes()).isEmpty();
assertThat(accessToken.getTokenValue()).isEqualTo(expectedAccessToken.getTokenValue());
assertThat(accessToken.getIssuedAt()).isEqualTo(expectedAccessToken.getIssuedAt());
assertThat(accessToken.getExpiresAt()).isEqualTo(expectedAccessToken.getExpiresAt());
assertThat(authorizedClient.getRefreshToken()).isNull();
}
private static String asJson(OAuth2AuthorizedClient authorizedClient) {
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.client.OAuth2AuthorizedClient\",\n" +
" \"clientRegistration\": " + asJson(authorizedClient.getClientRegistration()) + ",\n" +
" \"principalName\": \"" + authorizedClient.getPrincipalName() + "\",\n" +
" \"accessToken\": " + asJson(authorizedClient.getAccessToken()) + ",\n" +
" \"refreshToken\": " + asJson(authorizedClient.getRefreshToken()) + "\n" +
"}";
// @formatter:on
}
private static String asJson(ClientRegistration clientRegistration) {
ClientRegistration.ProviderDetails providerDetails = clientRegistration.getProviderDetails();
ClientRegistration.ProviderDetails.UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint();
String scopes = "";
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
scopes = StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), ",", "\"", "\"");
}
String configurationMetadata = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
if (!CollectionUtils.isEmpty(providerDetails.getConfigurationMetadata())) {
configurationMetadata += "," + providerDetails.getConfigurationMetadata().keySet().stream()
.map((key) -> "\"" + key + "\": \"" + providerDetails.getConfigurationMetadata().get(key) + "\"")
.collect(Collectors.joining(","));
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.client.registration.ClientRegistration\",\n" +
" \"registrationId\": \"" + clientRegistration.getRegistrationId() + "\",\n" +
" \"clientId\": \"" + clientRegistration.getClientId() + "\",\n" +
" \"clientSecret\": \"" + clientRegistration.getClientSecret() + "\",\n" +
" \"clientAuthenticationMethod\": {\n" +
" \"value\": \"" + clientRegistration.getClientAuthenticationMethod().getValue() + "\"\n" +
" },\n" +
" \"authorizationGrantType\": {\n" +
" \"value\": \"" + clientRegistration.getAuthorizationGrantType().getValue() + "\"\n" +
" },\n" +
" \"redirectUri\": \"" + clientRegistration.getRedirectUri() + "\",\n" +
" \"scopes\": [\n" +
" \"java.util.Collections$UnmodifiableSet\",\n" +
" [" + scopes + "]\n" +
" ],\n" +
" \"providerDetails\": {\n" +
" \"@class\": \"org.springframework.security.oauth2.client.registration.ClientRegistration$ProviderDetails\",\n" +
" \"authorizationUri\": \"" + providerDetails.getAuthorizationUri() + "\",\n" +
" \"tokenUri\": \"" + providerDetails.getTokenUri() + "\",\n" +
" \"userInfoEndpoint\": {\n" +
" \"@class\": \"org.springframework.security.oauth2.client.registration.ClientRegistration$ProviderDetails$UserInfoEndpoint\",\n" +
" \"uri\": " + ((userInfoEndpoint.getUri() != null) ? "\"" + userInfoEndpoint.getUri() + "\"" : null) + ",\n" +
" \"authenticationMethod\": {\n" +
" \"value\": \"" + userInfoEndpoint.getAuthenticationMethod().getValue() + "\"\n" +
" },\n" +
" \"userNameAttributeName\": " + ((userInfoEndpoint.getUserNameAttributeName() != null) ? "\"" + userInfoEndpoint.getUserNameAttributeName() + "\"" : null) + "\n" +
" },\n" +
" \"jwkSetUri\": " + ((providerDetails.getJwkSetUri() != null) ? "\"" + providerDetails.getJwkSetUri() + "\"" : null) + ",\n" +
" \"issuerUri\": " + ((providerDetails.getIssuerUri() != null) ? "\"" + providerDetails.getIssuerUri() + "\"" : null) + ",\n" +
" \"configurationMetadata\": {\n" +
" " + configurationMetadata + "\n" +
" }\n" +
" },\n" +
" \"clientName\": \"" + clientRegistration.getClientName() + "\"\n" +
"}";
// @formatter:on
}
private static String asJson(OAuth2AccessToken accessToken) {
String scopes = "";
if (!CollectionUtils.isEmpty(accessToken.getScopes())) {
scopes = StringUtils.collectionToDelimitedString(accessToken.getScopes(), ",", "\"", "\"");
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.OAuth2AccessToken\",\n" +
" \"tokenType\": {\n" +
" \"value\": \"" + accessToken.getTokenType().getValue() + "\"\n" +
" },\n" +
" \"tokenValue\": \"" + accessToken.getTokenValue() + "\",\n" +
" \"issuedAt\": " + toString(accessToken.getIssuedAt()) + ",\n" +
" \"expiresAt\": " + toString(accessToken.getExpiresAt()) + ",\n" +
" \"scopes\": [\n" +
" \"java.util.Collections$UnmodifiableSet\",\n" +
" [" + scopes + "]\n" +
" ]\n" +
"}";
// @formatter:on
}
private static String asJson(OAuth2RefreshToken refreshToken) {
if (refreshToken == null) {
return null;
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.OAuth2RefreshToken\",\n" +
" \"tokenValue\": \"" + refreshToken.getTokenValue() + "\",\n" +
" \"issuedAt\": " + toString(refreshToken.getIssuedAt()) + ",\n" +
" \"expiresAt\": " + toString(refreshToken.getExpiresAt()) + "\n" +
"}";
// @formatter:on
}
private static String toString(Instant instant) {
if (instant == null) {
return null;
}
return DecimalUtils.toBigDecimal(instant.getEpochSecond(), instant.getNano()).toString();
}
}
| 17,501 | 52.687117 | 175 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java | /*
* Copyright 2002-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.client.jackson2;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.DecimalUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.authentication.TestOAuth2AuthenticationTokens;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthenticationTokenMixin}.
*
* @author Joe Grandja
*/
public class OAuth2AuthenticationTokenMixinTests {
private ObjectMapper mapper;
@BeforeEach
public void setup() {
ClassLoader loader = getClass().getClassLoader();
this.mapper = new ObjectMapper();
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
// see https://github.com/FasterXML/jackson-databind/issues/3052 for details
this.mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
}
@Test
public void serializeWhenMixinRegisteredThenSerializes() throws Exception {
// OidcUser
OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
String expectedJson = asJson(authentication);
String json = this.mapper.writeValueAsString(authentication);
JSONAssert.assertEquals(expectedJson, json, true);
// OAuth2User
authentication = TestOAuth2AuthenticationTokens.authenticated();
expectedJson = asJson(authentication);
json = this.mapper.writeValueAsString(authentication);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception {
DefaultOidcUser principal = TestOidcUsers.create();
principal = new DefaultOidcUser(principal.getAuthorities(), principal.getIdToken());
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(principal, Collections.emptyList(),
"registration-id");
String expectedJson = asJson(authentication);
String json = this.mapper.writeValueAsString(authentication);
JSONAssert.assertEquals(expectedJson, json, true);
}
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
String json = asJson(authentication);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationToken.class));
}
@Test
public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception {
// OidcUser
OAuth2AuthenticationToken expectedAuthentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
String json = asJson(expectedAuthentication);
OAuth2AuthenticationToken authentication = this.mapper.readValue(json, OAuth2AuthenticationToken.class);
assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities());
assertThat(authentication.getDetails()).isEqualTo(expectedAuthentication.getDetails());
assertThat(authentication.isAuthenticated()).isEqualTo(expectedAuthentication.isAuthenticated());
assertThat(authentication.getAuthorizedClientRegistrationId())
.isEqualTo(expectedAuthentication.getAuthorizedClientRegistrationId());
DefaultOidcUser expectedOidcUser = (DefaultOidcUser) expectedAuthentication.getPrincipal();
DefaultOidcUser oidcUser = (DefaultOidcUser) authentication.getPrincipal();
assertThat(oidcUser.getAuthorities().containsAll(expectedOidcUser.getAuthorities())).isTrue();
assertThat(oidcUser.getAttributes()).containsExactlyEntriesOf(expectedOidcUser.getAttributes());
assertThat(oidcUser.getName()).isEqualTo(expectedOidcUser.getName());
OidcIdToken expectedIdToken = expectedOidcUser.getIdToken();
OidcIdToken idToken = oidcUser.getIdToken();
assertThat(idToken.getTokenValue()).isEqualTo(expectedIdToken.getTokenValue());
assertThat(idToken.getIssuedAt()).isEqualTo(expectedIdToken.getIssuedAt());
assertThat(idToken.getExpiresAt()).isEqualTo(expectedIdToken.getExpiresAt());
assertThat(idToken.getClaims()).containsExactlyEntriesOf(expectedIdToken.getClaims());
OidcUserInfo expectedUserInfo = expectedOidcUser.getUserInfo();
OidcUserInfo userInfo = oidcUser.getUserInfo();
assertThat(userInfo.getClaims()).containsExactlyEntriesOf(expectedUserInfo.getClaims());
// OAuth2User
expectedAuthentication = TestOAuth2AuthenticationTokens.authenticated();
json = asJson(expectedAuthentication);
authentication = this.mapper.readValue(json, OAuth2AuthenticationToken.class);
assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities());
assertThat(authentication.getDetails()).isEqualTo(expectedAuthentication.getDetails());
assertThat(authentication.isAuthenticated()).isEqualTo(expectedAuthentication.isAuthenticated());
assertThat(authentication.getAuthorizedClientRegistrationId())
.isEqualTo(expectedAuthentication.getAuthorizedClientRegistrationId());
DefaultOAuth2User expectedOauth2User = (DefaultOAuth2User) expectedAuthentication.getPrincipal();
DefaultOAuth2User oauth2User = (DefaultOAuth2User) authentication.getPrincipal();
assertThat(oauth2User.getAuthorities().containsAll(expectedOauth2User.getAuthorities())).isTrue();
assertThat(oauth2User.getAttributes()).containsExactlyEntriesOf(expectedOauth2User.getAttributes());
assertThat(oauth2User.getName()).isEqualTo(expectedOauth2User.getName());
}
@Test
public void deserializeWhenRequiredAttributesOnlyThenDeserializes() throws Exception {
DefaultOidcUser expectedPrincipal = TestOidcUsers.create();
expectedPrincipal = new DefaultOidcUser(expectedPrincipal.getAuthorities(), expectedPrincipal.getIdToken());
OAuth2AuthenticationToken expectedAuthentication = new OAuth2AuthenticationToken(expectedPrincipal,
Collections.emptyList(), "registration-id");
String json = asJson(expectedAuthentication);
OAuth2AuthenticationToken authentication = this.mapper.readValue(json, OAuth2AuthenticationToken.class);
assertThat(authentication.getAuthorities()).isEmpty();
assertThat(authentication.getDetails()).isEqualTo(expectedAuthentication.getDetails());
assertThat(authentication.isAuthenticated()).isEqualTo(expectedAuthentication.isAuthenticated());
assertThat(authentication.getAuthorizedClientRegistrationId())
.isEqualTo(expectedAuthentication.getAuthorizedClientRegistrationId());
DefaultOidcUser principal = (DefaultOidcUser) authentication.getPrincipal();
assertThat(principal.getAuthorities().containsAll(expectedPrincipal.getAuthorities())).isTrue();
assertThat(principal.getAttributes()).containsExactlyEntriesOf(expectedPrincipal.getAttributes());
assertThat(principal.getName()).isEqualTo(expectedPrincipal.getName());
OidcIdToken expectedIdToken = expectedPrincipal.getIdToken();
OidcIdToken idToken = principal.getIdToken();
assertThat(idToken.getTokenValue()).isEqualTo(expectedIdToken.getTokenValue());
assertThat(idToken.getIssuedAt()).isEqualTo(expectedIdToken.getIssuedAt());
assertThat(idToken.getExpiresAt()).isEqualTo(expectedIdToken.getExpiresAt());
assertThat(idToken.getClaims()).containsExactlyEntriesOf(expectedIdToken.getClaims());
assertThat(principal.getUserInfo()).isNull();
}
private static String asJson(OAuth2AuthenticationToken authentication) {
String principalJson = (authentication.getPrincipal() instanceof DefaultOidcUser)
? asJson((DefaultOidcUser) authentication.getPrincipal())
: asJson((DefaultOAuth2User) authentication.getPrincipal());
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken\",\n" +
" \"principal\": " + principalJson + ",\n" +
" \"authorities\": " + asJson(authentication.getAuthorities(), "java.util.Collections$UnmodifiableRandomAccessList") + ",\n" +
" \"authorizedClientRegistrationId\": \"" + authentication.getAuthorizedClientRegistrationId() + "\",\n" +
" \"details\": null\n" +
"}";
// @formatter:on
}
private static String asJson(DefaultOAuth2User oauth2User) {
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.user.DefaultOAuth2User\",\n" +
" \"authorities\": " + asJson(oauth2User.getAuthorities(), "java.util.Collections$UnmodifiableSet") + ",\n" +
" \"attributes\": {\n" +
" \"@class\": \"java.util.Collections$UnmodifiableMap\",\n" +
" \"username\": \"user\"\n" +
" },\n" +
" \"nameAttributeKey\": \"username\"\n" +
" }";
// @formatter:on
}
private static String asJson(DefaultOidcUser oidcUser) {
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser\",\n" +
" \"authorities\": " + asJson(oidcUser.getAuthorities(), "java.util.Collections$UnmodifiableSet") + ",\n" +
" \"idToken\": " + asJson(oidcUser.getIdToken()) + ",\n" +
" \"userInfo\": " + asJson(oidcUser.getUserInfo()) + ",\n" +
" \"nameAttributeKey\": \"" + IdTokenClaimNames.SUB + "\"\n" +
" }";
// @formatter:on
}
private static String asJson(Collection<? extends GrantedAuthority> authorities, String classTypeInfo) {
OAuth2UserAuthority oauth2UserAuthority = null;
OidcUserAuthority oidcUserAuthority = null;
List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
for (GrantedAuthority authority : authorities) {
if (authority instanceof OidcUserAuthority) {
oidcUserAuthority = (OidcUserAuthority) authority;
}
else if (authority instanceof OAuth2UserAuthority) {
oauth2UserAuthority = (OAuth2UserAuthority) authority;
}
else if (authority instanceof SimpleGrantedAuthority) {
simpleAuthorities.add((SimpleGrantedAuthority) authority);
}
}
String authoritiesJson = (oidcUserAuthority != null) ? asJson(oidcUserAuthority)
: (oauth2UserAuthority != null) ? asJson(oauth2UserAuthority) : "";
if (!simpleAuthorities.isEmpty()) {
if (StringUtils.hasLength(authoritiesJson)) {
authoritiesJson += ",";
}
authoritiesJson += asJson(simpleAuthorities);
}
// @formatter:off
return "[\n" +
" \"" + classTypeInfo + "\",\n" +
" [" + authoritiesJson + "]\n" +
" ]";
// @formatter:on
}
private static String asJson(OAuth2UserAuthority oauth2UserAuthority) {
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.user.OAuth2UserAuthority\",\n" +
" \"authority\": \"" + oauth2UserAuthority.getAuthority() + "\",\n" +
" \"attributes\": {\n" +
" \"@class\": \"java.util.Collections$UnmodifiableMap\",\n" +
" \"username\": \"user\"\n" +
" }\n" +
" }";
// @formatter:on
}
private static String asJson(OidcUserAuthority oidcUserAuthority) {
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority\",\n" +
" \"authority\": \"" + oidcUserAuthority.getAuthority() + "\",\n" +
" \"idToken\": " + asJson(oidcUserAuthority.getIdToken()) + ",\n" +
" \"userInfo\": " + asJson(oidcUserAuthority.getUserInfo()) + "\n" +
" }";
// @formatter:on
}
private static String asJson(List<SimpleGrantedAuthority> simpleAuthorities) {
// @formatter:off
return simpleAuthorities.stream()
.map((authority) -> "{\n" +
" \"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\",\n" +
" \"authority\": \"" + authority.getAuthority() + "\"\n" +
" }")
.collect(Collectors.joining(","));
// @formatter:on
}
private static String asJson(OidcIdToken idToken) {
String aud = "";
if (!CollectionUtils.isEmpty(idToken.getAudience())) {
aud = StringUtils.collectionToDelimitedString(idToken.getAudience(), ",", "\"", "\"");
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.oidc.OidcIdToken\",\n" +
" \"tokenValue\": \"" + idToken.getTokenValue() + "\",\n" +
" \"issuedAt\": " + toString(idToken.getIssuedAt()) + ",\n" +
" \"expiresAt\": " + toString(idToken.getExpiresAt()) + ",\n" +
" \"claims\": {\n" +
" \"@class\": \"java.util.Collections$UnmodifiableMap\",\n" +
" \"iat\": [\n" +
" \"java.time.Instant\",\n" +
" " + toString(idToken.getIssuedAt()) + "\n" +
" ],\n" +
" \"exp\": [\n" +
" \"java.time.Instant\",\n" +
" " + toString(idToken.getExpiresAt()) + "\n" +
" ],\n" +
" \"sub\": \"" + idToken.getSubject() + "\",\n" +
" \"iss\": \"" + idToken.getIssuer() + "\",\n" +
" \"aud\": [\n" +
" \"java.util.Collections$UnmodifiableSet\",\n" +
" [" + aud + "]\n" +
" ],\n" +
" \"azp\": \"" + idToken.getAuthorizedParty() + "\"\n" +
" }\n" +
" }";
// @formatter:on
}
private static String asJson(OidcUserInfo userInfo) {
if (userInfo == null) {
return null;
}
// @formatter:off
return "{\n" +
" \"@class\": \"org.springframework.security.oauth2.core.oidc.OidcUserInfo\",\n" +
" \"claims\": {\n" +
" \"@class\": \"java.util.Collections$UnmodifiableMap\",\n" +
" \"sub\": \"" + userInfo.getSubject() + "\",\n" +
" \"name\": \"" + userInfo.getClaim(StandardClaimNames.NAME) + "\"\n" +
" }\n" +
" }";
// @formatter:on
}
private static String toString(Instant instant) {
if (instant == null) {
return null;
}
return DecimalUtils.toBigDecimal(instant.getEpochSecond(), instant.getNano()).toString();
}
}
| 15,946 | 46.320475 | 131 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java | /*
* Copyright 2002-2022 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.client.oidc.userinfo;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OidcReactiveOAuth2UserServiceTests {
@Mock
private ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService;
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration()
.userNameAttributeName(IdTokenClaimNames.SUB);
private OidcIdToken idToken = TestOidcIdTokens.idToken().build();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token",
Instant.now(), Instant.now().plus(Duration.ofDays(1)), Collections.singleton("read:user"));
private OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService();
@BeforeEach
public void setup() {
this.userService.setOauth2UserService(this.oauth2UserService);
}
@Test
public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() {
Map<String, Converter<Object, ?>> claimTypeConverters = OidcReactiveOAuth2UserService
.createDefaultClaimTypeConverters();
assertThat(claimTypeConverters).containsKey(StandardClaimNames.EMAIL_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.PHONE_NUMBER_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.UPDATED_AT);
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
}
@Test
public void loadUserWhenUserInfoUriNullThenUserInfoNotRetrieved() {
this.registration.userInfoUri(null);
OidcUser user = this.userService.loadUser(userRequest()).block();
assertThat(user.getUserInfo()).isNull();
}
@Test
public void loadUserWhenOAuth2UserEmptyThenNullUserInfo() {
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.empty());
OidcUser user = this.userService.loadUser(userRequest()).block();
assertThat(user.getUserInfo()).isNull();
}
@Test
public void loadUserWhenOAuth2UserSubjectNullThenOAuth2AuthenticationException() {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
}
@Test
public void loadUserWhenOAuth2UserSubjectNotEqualThenOAuth2AuthenticationException() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "not-equal");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
}
@Test
public void loadUserWhenOAuth2UserThenUserInfoNotNull() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThat(this.userService.loadUser(userRequest()).block().getUserInfo()).isNotNull();
}
@Test
public void loadUserWhenOAuth2UserAndUser() {
this.registration.userNameAttributeName("user");
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThat(this.userService.loadUser(userRequest()).block().getName()).isEqualTo("rob");
}
@Test
public void loadUserWhenCustomClaimTypeConverterFactorySetThenApplied() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
OidcUserRequest userRequest = userRequest();
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(
Function.class);
this.userService.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
given(customClaimTypeConverterFactory.apply(same(userRequest.getClientRegistration())))
.willReturn(new ClaimTypeConverter(OidcReactiveOAuth2UserService.createDefaultClaimTypeConverters()));
this.userService.loadUser(userRequest).block().getUserInfo();
verify(customClaimTypeConverterFactory).apply(same(userRequest.getClientRegistration()));
}
@Test
public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() {
OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService();
OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.scopes("message:read", "message:write"), TestOidcIdTokens.idToken().build());
OidcUser user = userService.loadUser(request).block();
assertThat(user.getAuthorities()).hasSize(3);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:read"));
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:write"));
}
@Test
public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService();
OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.noScopes(), TestOidcIdTokens.idToken().build());
OidcUser user = userService.loadUser(request).block();
assertThat(user.getAuthorities()).hasSize(1);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OIDC_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
private OidcUserRequest userRequest() {
return new OidcUserRequest(this.registration.build(), this.accessToken, this.idToken);
}
}
| 10,003 | 46.412322 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestUtilsTests.java | /*
* Copyright 2002-2022 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.client.oidc.userinfo;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 5.1
*/
public class OidcUserRequestUtilsTests {
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
OidcIdToken idToken = TestOidcIdTokens.idToken().build();
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(),
Instant.now().plus(Duration.ofDays(1)), Collections.singleton("read:user"));
@Test
public void shouldRetrieveUserInfoWhenEndpointDefinedAndScopesOverlapThenTrue() {
assertThat(OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest())).isTrue();
}
@Test
public void shouldRetrieveUserInfoWhenNoUserInfoUriThenFalse() {
this.registration.userInfoUri(null);
assertThat(OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest())).isFalse();
}
@Test
public void shouldRetrieveUserInfoWhenDifferentScopesThenFalse() {
this.registration.scope("notintoken");
assertThat(OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest())).isFalse();
}
@Test
public void shouldRetrieveUserInfoWhenNotAuthorizationCodeThenFalse() {
this.registration.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS);
assertThat(OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest())).isFalse();
}
private OidcUserRequest userRequest() {
return new OidcUserRequest(this.registration.build(), this.accessToken, this.idToken);
}
}
| 2,728 | 35.386667 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java | /*
* Copyright 2002-2018 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.client.oidc.userinfo;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OidcUserRequest}.
*
* @author Joe Grandja
*/
public class OidcUserRequestTests {
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private OidcIdToken idToken;
private Map<String, Object> additionalParameters;
@BeforeEach
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", Instant.now(),
Instant.now().plusSeconds(60), new LinkedHashSet<>(Arrays.asList("scope1", "scope2")));
this.idToken = TestOidcIdTokens.idToken().authorizedParty(this.clientRegistration.getClientId()).build();
this.additionalParameters = new HashMap<>();
this.additionalParameters.put("param1", "value1");
this.additionalParameters.put("param2", "value2");
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken));
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken));
}
@Test
public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null));
}
@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OidcUserRequest userRequest = new OidcUserRequest(this.clientRegistration, this.accessToken, this.idToken,
this.additionalParameters);
assertThat(userRequest.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(userRequest.getAccessToken()).isEqualTo(this.accessToken);
assertThat(userRequest.getIdToken()).isEqualTo(this.idToken);
assertThat(userRequest.getAdditionalParameters()).containsAllEntriesOf(this.additionalParameters);
}
}
| 3,504 | 37.097826 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java | /*
* Copyright 2002-2022 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.client.oidc.userinfo;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
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.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link OidcUserService}.
*
* @author Joe Grandja
*/
public class OidcUserServiceTests {
private ClientRegistration.Builder clientRegistrationBuilder;
private OAuth2AccessToken accessToken;
private OidcIdToken idToken;
private OidcUserService userService = new OidcUserService();
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().userInfoUri(null)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.userNameAttributeName(StandardClaimNames.SUB);
this.accessToken = TestOAuth2AccessTokens.scopes(OidcScopes.OPENID, OidcScopes.PROFILE);
Map<String, Object> idTokenClaims = new HashMap<>();
idTokenClaims.put(IdTokenClaimNames.ISS, "https://provider.com");
idTokenClaims.put(IdTokenClaimNames.SUB, "subject1");
this.idToken = new OidcIdToken("access-token", Instant.MIN, Instant.MAX, idTokenClaims);
this.userService.setOauth2UserService(new DefaultOAuth2UserService());
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() {
Map<String, Converter<Object, ?>> claimTypeConverters = OidcUserService.createDefaultClaimTypeConverters();
assertThat(claimTypeConverters).containsKey(StandardClaimNames.EMAIL_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.PHONE_NUMBER_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.UPDATED_AT);
}
@Test
public void setOauth2UserServiceWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setOauth2UserService(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
}
@Test
public void setAccessibleScopesWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setAccessibleScopes(null));
}
@Test
public void setAccessibleScopesWhenEmptyThenSet() {
this.userService.setAccessibleScopes(Collections.emptySet());
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
public void loadUserWhenUserInfoUriIsNullThenUserInfoEndpointNotRequested() {
OidcUser user = this.userService
.loadUser(new OidcUserRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNull();
}
@Test
public void loadUserWhenNonStandardScopesAuthorizedThenUserInfoEndpointNotRequested() {
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri("https://provider.com/user")
.build();
this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2");
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNull();
}
// gh-6886
@Test
public void loadUserWhenNonStandardScopesAuthorizedAndAccessibleScopesMatchThenUserInfoEndpointRequested() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2");
this.userService.setAccessibleScopes(Collections.singleton("scope2"));
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNotNull();
}
// gh-6886
@Test
public void loadUserWhenNonStandardScopesAuthorizedAndAccessibleScopesEmptyThenUserInfoEndpointRequested() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2");
this.userService.setAccessibleScopes(Collections.emptySet());
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNotNull();
}
// gh-6886
@Test
public void loadUserWhenStandardScopesAuthorizedThenUserInfoEndpointRequested() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNotNull();
}
@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getIdToken()).isNotNull();
assertThat(user.getUserInfo()).isNotNull();
assertThat(user.getUserInfo().getClaims().size()).isEqualTo(6);
assertThat(user.getIdToken()).isEqualTo(this.idToken);
assertThat(user.getName()).isEqualTo("subject1");
assertThat(user.getUserInfo().getSubject()).isEqualTo("subject1");
assertThat(user.getUserInfo().getFullName()).isEqualTo("first last");
assertThat(user.getUserInfo().getGivenName()).isEqualTo("first");
assertThat(user.getUserInfo().getFamilyName()).isEqualTo("last");
assertThat(user.getUserInfo().getPreferredUsername()).isEqualTo("user1");
assertThat(user.getUserInfo().getEmail()).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(3);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OidcUserAuthority.class);
OidcUserAuthority userAuthority = (OidcUserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OIDC_USER");
assertThat(userAuthority.getIdToken()).isEqualTo(user.getIdToken());
assertThat(userAuthority.getUserInfo()).isEqualTo(user.getUserInfo());
}
// gh-5447
@Test
public void loadUserWhenUserInfoSuccessResponseAndUserInfoSubjectIsNullThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"email\": \"full_name@provider.com\",\n"
+ " \"name\": \"full name\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userNameAttributeName(StandardClaimNames.EMAIL).build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoSuccessResponseAndUserInfoSubjectNotSameAsIdTokenSubjectThenThrowOAuth2AuthenticationException() {
String userInfoResponse = "{\n" + " \"sub\": \"other-subject\"\n" + "}\n";
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenCustomUserNameAttributeNameThenGetNameReturnsCustomUserName() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userNameAttributeName(StandardClaimNames.EMAIL).build();
OidcUser user = this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getName()).isEqualTo("user1@example.com");
}
// gh-5294
@Test
public void loadUserWhenUserInfoSuccessResponseThenAcceptHeaderJson() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(this.server.takeRequest(1, TimeUnit.SECONDS).getHeader(HttpHeaders.ACCEPT))
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.GET.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodFormSuccessResponseThenHttpMethodPost() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
assertThat(request.getBody().readUtf8()).isEqualTo("access_token=" + this.accessToken.getTokenValue());
}
@Test
public void loadUserWhenCustomClaimTypeConverterFactorySetThenApplied() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(
Function.class);
this.userService.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
given(customClaimTypeConverterFactory.apply(same(clientRegistration)))
.willReturn(new ClaimTypeConverter(OidcUserService.createDefaultClaimTypeConverters()));
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
@Test
public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() {
OidcUserService userService = new OidcUserService();
OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.scopes("message:read", "message:write"), TestOidcIdTokens.idToken().build());
OidcUser user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(3);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OidcUserAuthority.class);
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:read"));
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:write"));
}
@Test
public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
OidcUserService userService = new OidcUserService();
OidcUserRequest request = new OidcUserRequest(this.clientRegistrationBuilder.build(),
TestOAuth2AccessTokens.noScopes(), this.idToken);
OidcUser user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(1);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OidcUserAuthority.class);
}
@Test
public void loadUserWhenTokenDoesNotContainScopesAndUserInfoUriThenUserInfoRequested() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
+ " \"name\": \"first last\",\n"
+ " \"given_name\": \"first\",\n"
+ " \"family_name\": \"last\",\n"
+ " \"preferred_username\": \"user1\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
OidcUserService userService = new OidcUserService();
OidcUserRequest request = new OidcUserRequest(clientRegistration, TestOAuth2AccessTokens.noScopes(),
this.idToken);
OidcUser user = userService.loadUser(request);
assertThat(user.getUserInfo()).isNotNull();
}
private MockResponse jsonResponse(String json) {
// @formatter:off
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(json);
// @formatter:on
}
}
| 22,677 | 44.356 | 131 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java | /*
* Copyright 2002-2022 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.client.oidc.web.logout;
import java.io.IOException;
import java.util.Collections;
import jakarta.servlet.ServletException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
import org.springframework.security.oauth2.core.user.TestOAuth2Users;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OidcClientInitiatedLogoutSuccessHandler}
*/
@ExtendWith(MockitoExtension.class)
public class OidcClientInitiatedLogoutSuccessHandlerTests {
// @formatter:off
ClientRegistration registration = TestClientRegistrations
.clientRegistration()
.providerConfigurationMetadata(Collections.singletonMap("end_session_endpoint", "https://endpoint"))
.build();
// @formatter:on
ClientRegistrationRepository repository = new InMemoryClientRegistrationRepository(this.registration);
MockHttpServletRequest request;
MockHttpServletResponse response;
OidcClientInitiatedLogoutSuccessHandler handler;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.handler = new OidcClientInitiatedLogoutSuccessHandler(this.repository);
}
@Test
public void logoutWhenOidcRedirectUrlConfiguredThenRedirects() throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://endpoint?id_token_hint=id-token");
}
@Test
public void logoutWhenNotOAuth2AuthenticationThenDefaults() throws IOException, ServletException {
Authentication token = mock(Authentication.class);
this.request.setUserPrincipal(token);
this.handler.setDefaultTargetUrl("https://default");
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://default");
}
@Test
public void logoutWhenNotOidcUserThenDefaults() throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOAuth2Users.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.request.setUserPrincipal(token);
this.handler.setDefaultTargetUrl("https://default");
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://default");
}
@Test
public void logoutWhenClientRegistrationHasNoEndSessionEndpointThenDefaults() throws Exception {
ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
ClientRegistrationRepository repository = new InMemoryClientRegistrationRepository(registration);
OidcClientInitiatedLogoutSuccessHandler handler = new OidcClientInitiatedLogoutSuccessHandler(repository);
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, registration.getRegistrationId());
this.request.setUserPrincipal(token);
handler.setDefaultTargetUrl("https://default");
handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://default");
}
@Test
public void logoutWhenUsingPostLogoutBaseUrlRedirectUriTemplateThenBuildsItForRedirect()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.handler.setPostLogoutRedirectUri("{baseUrl}");
this.request.setScheme("https");
this.request.setServerPort(443);
this.request.setServerName("rp.example.org");
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirect()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.handler.setPostLogoutRedirectUri("{baseScheme}://{baseHost}{basePort}{basePath}");
this.request.setScheme("https");
this.request.setServerPort(443);
this.request.setServerName("rp.example.org");
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateWithOtherPortThenBuildsItForRedirect()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.handler.setPostLogoutRedirectUri("{baseScheme}://{baseHost}{basePort}{basePath}");
this.request.setScheme("https");
this.request.setServerPort(400);
this.request.setServerName("rp.example.org");
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://endpoint?" + "id_token_hint=id-token&"
+ "post_logout_redirect_uri=https://rp.example.org:400");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirectExpanded()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.handler.setPostLogoutRedirectUri("{baseUrl}/{registrationId}");
this.request.setScheme("https");
this.request.setServerPort(443);
this.request.setServerName("rp.example.org");
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo(String.format(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org/%s",
this.registration.getRegistrationId()));
}
// gh-9511
@Test
public void logoutWhenUsingPostLogoutRedirectUriWithQueryParametersThenBuildsItForRedirect()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
this.handler.setPostLogoutRedirectUri("https://rp.example.org/context?forwardUrl=secured%3Fparam%3Dtrue");
this.request.setUserPrincipal(token);
this.handler.onLogoutSuccess(this.request, this.response, token);
assertThat(this.response.getRedirectedUrl()).isEqualTo("https://endpoint?id_token_hint=id-token&"
+ "post_logout_redirect_uri=https://rp.example.org/context?forwardUrl%3Dsecured%253Fparam%253Dtrue");
}
@Test
public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
}
}
| 9,154 | 46.435233 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java | /*
* Copyright 2002-2022 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.client.oidc.web.server.logout;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import jakarta.servlet.ServletException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
import org.springframework.security.oauth2.core.user.TestOAuth2Users;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OidcClientInitiatedServerLogoutSuccessHandler}
*/
public class OidcClientInitiatedServerLogoutSuccessHandlerTests {
// @formatter:off
ClientRegistration registration = TestClientRegistrations
.clientRegistration()
.providerConfigurationMetadata(Collections.singletonMap("end_session_endpoint", "https://endpoint"))
.build();
// @formatter:on
ReactiveClientRegistrationRepository repository = new InMemoryReactiveClientRegistrationRepository(
this.registration);
ServerWebExchange exchange;
WebFilterChain chain;
OidcClientInitiatedServerLogoutSuccessHandler handler;
@BeforeEach
public void setup() {
this.exchange = mock(ServerWebExchange.class);
given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse());
given(this.exchange.getRequest()).willReturn(MockServerHttpRequest.get("/").build());
this.chain = mock(WebFilterChain.class);
this.handler = new OidcClientInitiatedServerLogoutSuccessHandler(this.repository);
}
@Test
public void logoutWhenOidcRedirectUrlConfiguredThenRedirects() {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://endpoint?id_token_hint=id-token");
}
@Test
public void logoutWhenNotOAuth2AuthenticationThenDefaults() {
Authentication token = mock(Authentication.class);
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setLogoutSuccessUrl(URI.create("https://default"));
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://default");
}
@Test
public void logoutWhenNotOidcUserThenDefaults() {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOAuth2Users.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setLogoutSuccessUrl(URI.create("https://default"));
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://default");
}
@Test
public void logoutWhenClientRegistrationHasNoEndSessionEndpointThenDefaults() {
ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
ReactiveClientRegistrationRepository repository = new InMemoryReactiveClientRegistrationRepository(
registration);
OidcClientInitiatedServerLogoutSuccessHandler handler = new OidcClientInitiatedServerLogoutSuccessHandler(
repository);
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
handler.setLogoutSuccessUrl(URI.create("https://default"));
handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://default");
}
@Test
public void logoutWhenUsingPostLogoutBaseUrlRedirectUriTemplateThenBuildsItForRedirect()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
MockServerHttpRequest request = MockServerHttpRequest.get("https://rp.example.org/").build();
given(this.exchange.getRequest()).willReturn(request);
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setPostLogoutRedirectUri("{baseUrl}");
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org");
}
// gh-11379
@Test
public void logoutWhenUsingPostLogoutRedirectUriWithQueryParametersThenBuildsItForRedirect() {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
this.handler.setPostLogoutRedirectUri("https://rp.example.org/context?forwardUrl=secured%3Fparam%3Dtrue");
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://endpoint?id_token_hint=id-token&"
+ "post_logout_redirect_uri=https://rp.example.org/context?forwardUrl%3Dsecured%253Fparam%253Dtrue");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirect() {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
MockServerHttpRequest request = MockServerHttpRequest.get("https://rp.example.org/").build();
given(this.exchange.getRequest()).willReturn(request);
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setPostLogoutRedirectUri("{baseScheme}://{baseHost}{basePort}{basePath}");
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateWithOtherPortThenBuildsItForRedirect() {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
MockServerHttpRequest request = MockServerHttpRequest.get("https://rp.example.org:400").build();
given(this.exchange.getRequest()).willReturn(request);
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setPostLogoutRedirectUri("{baseScheme}://{baseHost}{basePort}{basePath}");
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://endpoint?" + "id_token_hint=id-token&"
+ "post_logout_redirect_uri=https://rp.example.org:400");
}
@Test
public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirectExpanded()
throws IOException, ServletException {
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
given(this.exchange.getPrincipal()).willReturn(Mono.just(token));
MockServerHttpRequest request = MockServerHttpRequest.get("https://rp.example.org/").build();
given(this.exchange.getRequest()).willReturn(request);
WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain);
this.handler.setPostLogoutRedirectUri("{baseUrl}/{registrationId}");
this.handler.onLogoutSuccess(f, token).block();
assertThat(redirectedUrl(this.exchange)).isEqualTo(String.format(
"https://endpoint?" + "id_token_hint=id-token&" + "post_logout_redirect_uri=https://rp.example.org/%s",
this.registration.getRegistrationId()));
}
@Test
public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
}
private String redirectedUrl(ServerWebExchange exchange) {
return exchange.getResponse().getHeaders().getFirst("Location");
}
}
| 10,361 | 49.057971 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java | /*
* Copyright 2002-2019 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.client.oidc.authentication;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
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.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Joe Grandja
* @author Rafael Dominguez
* @since 5.2
*/
public class OidcIdTokenDecoderFactoryTests {
// @formatter:off
private ClientRegistration.Builder registration = TestClientRegistrations
.clientRegistration()
.scope("openid");
// @formatter:on
private OidcIdTokenDecoderFactory idTokenDecoderFactory;
@BeforeEach
public void setUp() {
this.idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
}
@Test
public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() {
Map<String, Converter<Object, ?>> claimTypeConverters = OidcIdTokenDecoderFactory
.createDefaultClaimTypeConverters();
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.ISS);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AUD);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.NONCE);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.EXP);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.IAT);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AUTH_TIME);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AMR);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.EMAIL_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.PHONE_NUMBER_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.UPDATED_AT);
}
@Test
public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
}
@Test
public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
}
@Test
public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
}
@Test
public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@Test
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@Test
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the client secret.");
}
@Test
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
}
@Test
public void createDecoderWhenClientRegistrationValidThenReturnDecoder() {
assertThat(this.idTokenDecoderFactory.createDecoder(this.registration.build())).isNotNull();
}
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customJwtValidatorFactory.apply(same(clientRegistration)))
.willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
ClientRegistration clientRegistration = this.registration.build();
given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
@Test
public void createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied() {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(
Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customClaimTypeConverterFactory.apply(same(clientRegistration)))
.willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
}
| 8,654 | 46.554945 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java | /*
* Copyright 2002-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.client.oidc.authentication;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.TestJwts;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
@Mock
private ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
@Mock
private ReactiveJwtDecoder jwtDecoder;
// @formatter:off
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration()
.scope("openid");
// @formatter:on
// @formatter:off
private OAuth2AuthorizationResponse.Builder authorizationResponseBldr = OAuth2AuthorizationResponse.success("code")
.state("state");
// @formatter:on
private OidcIdToken idToken = TestOidcIdTokens.idToken().build();
private OidcAuthorizationCodeReactiveAuthenticationManager manager;
private StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private String nonceHash;
@BeforeEach
public void setup() {
this.manager = new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService);
}
@Test
public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
this.accessTokenResponseClient = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService));
}
@Test
public void constructorWhenNullUserServiceThenIllegalArgumentException() {
this.userService = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService));
}
@Test
public void setJwtDecoderFactoryWhenNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setJwtDecoderFactory(null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
}
@Test
public void authenticateWhenNoSubscriptionThenDoesNothing() {
// we didn't do anything because it should cause a ClassCastException (as verified
// below)
TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
this.manager.authenticate(token);
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test
public void authenticationWhenNotOidcThenEmpty() {
this.registration.scope("notopenid");
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
}
@Test
public void authenticationWhenErrorThenOAuth2AuthenticationException() {
// @formatter:off
this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error")
.state("state");
// @formatter:on
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
this.authorizationResponseBldr.state("notmatch");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticateWhenIdTokenValidationErrorThenOAuth2AuthenticationException() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue()))
.build();
// @formatter:on
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block())
.withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
@Test
public void authenticateWhenIdTokenInvalidNonceThenOAuth2AuthenticationException() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(
Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue()))
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "sub");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block())
.withMessageContaining("[invalid_nonce]");
}
@Test
public void authenticationWhenOAuth2UserNotFoundThenEmpty() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN,
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."))
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.userService.loadUser(any())).willReturn(Mono.empty());
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
assertThat(this.manager.authenticate(authorizationCodeAuthentication).block()).isNull();
}
@Test
public void authenticationWhenOAuth2UserFoundThenSuccess() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(
Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue()))
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager
.authenticate(authorizationCodeAuthentication).block();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
assertThat(result.isAuthenticated()).isTrue();
}
@Test
public void authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(
Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue()))
.refreshToken("refresh-token")
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager
.authenticate(authorizationCodeAuthentication).block();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
assertThat(result.isAuthenticated()).isTrue();
assertThat(result.getRefreshToken().getTokenValue()).isNotNull();
}
// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
ClientRegistration clientRegistration = this.registration.build();
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue());
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Arrays.asList(clientRegistration.getClientId()));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
this.manager.authenticate(authorizationCodeAuthentication).block();
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
ClientRegistration clientRegistration = this.registration.build();
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.additionalParameters(
Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue()))
.build();
// @formatter:on
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId()));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
this.manager.setAuthoritiesMapper(authoritiesMapper);
Authentication result = this.manager.authenticate(authorizationCodeAuthentication).block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
private OAuth2AuthorizationCodeAuthenticationToken loginToken() {
ClientRegistration clientRegistration = this.registration.build();
Map<String, Object> attributes = new HashMap<>();
Map<String, Object> additionalParameters = new HashMap<>();
try {
String nonce = this.secureKeyGenerator.generateKey();
this.nonceHash = OidcAuthorizationCodeReactiveAuthenticationManager.createHash(nonce);
attributes.put(OidcParameterNames.NONCE, nonce);
additionalParameters.put(OidcParameterNames.NONCE, this.nonceHash);
}
catch (NoSuchAlgorithmException ex) {
}
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.state("state")
.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(clientRegistration.getRedirectUri())
.scopes(clientRegistration.getScopes())
.additionalParameters(additionalParameters)
.attributes(attributes).build();
OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr
.redirectUri(clientRegistration.getRedirectUri())
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, authorizationExchange);
}
}
| 19,648 | 48.744304 | 122 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java | /*
* Copyright 2002-2019 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.client.oidc.authentication;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.TestJwts;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OidcAuthorizationCodeAuthenticationProvider}.
*
* @author Joe Grandja
* @author Mark Heckler
*/
public class OidcAuthorizationCodeAuthenticationProviderTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizationRequest authorizationRequest;
private OAuth2AuthorizationResponse authorizationResponse;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private OAuth2AccessTokenResponse accessTokenResponse;
private OAuth2UserService<OidcUserRequest, OidcUser> userService;
private OidcAuthorizationCodeAuthenticationProvider authenticationProvider;
private StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private String nonceHash;
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().clientId("client1").build();
Map<String, Object> attributes = new HashMap<>();
Map<String, Object> additionalParameters = new HashMap<>();
try {
String nonce = this.secureKeyGenerator.generateKey();
this.nonceHash = OidcAuthorizationCodeAuthenticationProvider.createHash(nonce);
attributes.put(OidcParameterNames.NONCE, nonce);
additionalParameters.put(OidcParameterNames.NONCE, this.nonceHash);
}
catch (NoSuchAlgorithmException ex) {
}
// @formatter:off
this.authorizationRequest = TestOAuth2AuthorizationRequests.request()
.scope("openid", "profile", "email")
.attributes(attributes)
.additionalParameters(additionalParameters)
.build();
this.authorizationResponse = TestOAuth2AuthorizationResponses.success()
.build();
// @formatter:on
this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
this.authorizationResponse);
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.accessTokenResponse = this.accessTokenSuccessResponse();
this.userService = mock(OAuth2UserService.class);
this.authenticationProvider = new OidcAuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient,
this.userService);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(this.accessTokenResponse);
}
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeAuthenticationProvider(null, this.userService));
}
@Test
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new OidcAuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient, null));
}
@Test
public void setJwtDecoderFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setJwtDecoderFactory(null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setAuthoritiesMapper(null));
}
@Test
public void supportsWhenTypeOAuth2LoginAuthenticationTokenThenReturnTrue() {
assertThat(this.authenticationProvider.supports(OAuth2LoginAuthenticationToken.class)).isTrue();
}
@Test
public void authenticateWhenAuthorizationRequestDoesNotContainOpenidScopeThenReturnNull() {
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.scope("scope1")
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
this.authorizationResponse);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThat(authentication).isNull();
}
@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
// @formatter:off
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_SCOPE)
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_SCOPE);
}
@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
// @formatter:off
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success()
.state("89012")
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test
public void authenticateWhenTokenResponseDoesNotContainIdTokenThenThrowOAuth2AuthenticationException() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withResponse(this.accessTokenSuccessResponse())
.additionalParameters(Collections.emptyMap())
.build();
// @formatter:on
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("invalid_id_token");
}
@Test
public void authenticateWhenJwkSetUriNotSetThenThrowOAuth2AuthenticationException() {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.jwkSetUri(null)
.build();
// @formatter:on
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(clientRegistration, this.authorizationExchange)))
.withMessageContaining("missing_signature_verifier");
}
@Test
public void authenticateWhenIdTokenValidationErrorThenThrowOAuth2AuthenticationException() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
given(jwtDecoder.decode(anyString())).willThrow(new JwtException("ID Token Validation Error"));
this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
@Test
public void authenticateWhenIdTokenInvalidNonceThenThrowOAuth2AuthenticationException() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
this.setUpIdToken(claims);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("[invalid_nonce]");
}
@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getPrincipal()).isEqualTo(principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(authorities);
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(this.accessTokenResponse.getAccessToken());
assertThat(authentication.getRefreshToken()).isEqualTo(this.accessTokenResponse.getRefreshToken());
}
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
.containsAllEntriesOf(this.accessTokenResponse.getAdditionalParameters());
}
private void setUpIdToken(Map<String, Object> claims) {
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
given(jwtDecoder.decode(anyString())).willReturn(idToken);
this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
}
private OAuth2AccessTokenResponse accessTokenSuccessResponse() {
Instant expiresAt = Instant.now().plusSeconds(5);
Set<String> scopes = new LinkedHashSet<>(Arrays.asList("openid", "profile", "email"));
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
// @formatter:off
return OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(expiresAt.getEpochSecond())
.scopes(scopes)
.refreshToken("refresh-token-1234")
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
}
| 17,338 | 47.842254 | 130 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java | /*
* Copyright 2002-2019 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.client.oidc.authentication;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
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.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Joe Grandja
* @author Rafael Dominguez
* @since 5.2
*/
public class ReactiveOidcIdTokenDecoderFactoryTests {
// @formatter:off
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration()
.scope("openid");
// @formatter:on
private ReactiveOidcIdTokenDecoderFactory idTokenDecoderFactory;
@BeforeEach
public void setUp() {
this.idTokenDecoderFactory = new ReactiveOidcIdTokenDecoderFactory();
}
@Test
public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() {
Map<String, Converter<Object, ?>> claimTypeConverters = ReactiveOidcIdTokenDecoderFactory
.createDefaultClaimTypeConverters();
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.ISS);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AUD);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.NONCE);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.EXP);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.IAT);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AUTH_TIME);
assertThat(claimTypeConverters).containsKey(IdTokenClaimNames.AMR);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.EMAIL_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.PHONE_NUMBER_VERIFIED);
assertThat(claimTypeConverters).containsKey(StandardClaimNames.UPDATED_AT);
}
@Test
public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
}
@Test
public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
}
@Test
public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
}
@Test
public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@Test
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@Test
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the client secret.");
}
@Test
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
}
@Test
public void createDecoderWhenClientRegistrationValidThenReturnDecoder() {
assertThat(this.idTokenDecoderFactory.createDecoder(this.registration.build())).isNotNull();
}
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customJwtValidatorFactory.apply(same(clientRegistration)))
.willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
ClientRegistration clientRegistration = this.registration.build();
given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
@Test
public void createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied() {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(
Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customClaimTypeConverterFactory.apply(same(clientRegistration)))
.willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
}
| 8,682 | 46.972376 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java | /*
* Copyright 2002-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.client.oidc.authentication;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import org.springframework.security.oauth2.jwt.Jwt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
*/
public class OidcIdTokenValidatorTests {
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
private Map<String, Object> headers = new HashMap<>();
private Map<String, Object> claims = new HashMap<>();
private Instant issuedAt = Instant.now();
private Instant expiresAt = this.issuedAt.plusSeconds(3600);
private Duration clockSkew = Duration.ofSeconds(60);
@BeforeEach
public void setup() {
this.headers.put("alg", JwsAlgorithms.RS256);
this.claims.put(IdTokenClaimNames.ISS, "https://example.com");
this.claims.put(IdTokenClaimNames.SUB, "rob");
this.claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client-id"));
}
@Test
public void validateWhenValidThenNoErrors() {
assertThat(this.validateIdToken()).isEmpty();
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> idTokenValidator.setClockSkew(null));
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1)));
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> idTokenValidator.setClock(null));
// @formatter:on
}
@Test
public void validateWhenIssuerNullThenHasErrors() {
this.claims.remove(IdTokenClaimNames.ISS);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.ISS));
// @formatter:on
}
@Test
public void validateWhenMetadataIssuerMismatchThenHasErrors() {
/*
* When the issuer is set in the provider metadata, and it does not match the
* issuer in the ID Token, the validation must fail
*/
this.registration = this.registration.issuerUri("https://somethingelse.com");
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.ISS));
// @formatter:on
}
@Test
public void validateWhenMetadataIssuerMatchThenNoErrors() {
/*
* When the issuer is set in the provider metadata, and it does match the issuer
* in the ID Token, the validation must succeed
*/
this.registration = this.registration.issuerUri("https://example.com");
assertThat(this.validateIdToken()).isEmpty();
}
@Test
public void validateWhenSubNullThenHasErrors() {
this.claims.remove(IdTokenClaimNames.SUB);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.SUB));
// @formatter:on
}
@Test
public void validateWhenAudNullThenHasErrors() {
this.claims.remove(IdTokenClaimNames.AUD);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD));
// @formatter:on
}
@Test
public void validateWhenIssuedAtNullThenHasErrors() {
this.issuedAt = null;
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT));
// @formatter:on
}
@Test
public void validateWhenExpiresAtNullThenHasErrors() {
this.expiresAt = null;
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
}
@Test
public void validateWhenAudMultipleAndAzpNullThenHasErrors() {
this.claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id", "other"));
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
// @formatter:on
}
@Test
public void validateWhenAzpNotClientIdThenHasErrors() {
this.claims.put(IdTokenClaimNames.AZP, "other");
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
// @formatter:on
}
@Test
public void validateWhenMultipleAudAzpClientIdThenNoErrors() {
this.claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id", "other"));
this.claims.put(IdTokenClaimNames.AZP, "client-id");
assertThat(this.validateIdToken()).isEmpty();
}
@Test
public void validateWhenMultipleAudAzpNotClientIdThenHasErrors() {
this.claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id-1", "client-id-2"));
this.claims.put(IdTokenClaimNames.AZP, "other-client");
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
// @formatter:on
}
@Test
public void validateWhenAudNotClientIdThenHasErrors() {
this.claims.put(IdTokenClaimNames.AUD, Collections.singletonList("other-client"));
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD));
// @formatter:on
}
@Test
public void validateWhenExpiredAnd60secClockSkewThenNoErrors() {
this.issuedAt = Instant.now().minus(Duration.ofSeconds(60));
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(30));
this.clockSkew = Duration.ofSeconds(60);
assertThat(this.validateIdToken()).isEmpty();
}
@Test
public void validateWhenExpiredAnd0secClockSkewThenHasErrors() {
this.issuedAt = Instant.now().minus(Duration.ofSeconds(60));
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(30));
this.clockSkew = Duration.ofSeconds(0);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
// @formatter:on
}
@Test
public void validateWhenIssuedAt5minAheadAnd5minClockSkewThenNoErrors() {
this.issuedAt = Instant.now().plus(Duration.ofMinutes(5));
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(60));
this.clockSkew = Duration.ofMinutes(5);
assertThat(this.validateIdToken()).isEmpty();
}
@Test
public void validateWhenIssuedAt1minAheadAnd0minClockSkewThenHasErrors() {
this.issuedAt = Instant.now().plus(Duration.ofMinutes(1));
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(60));
this.clockSkew = Duration.ofMinutes(0);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT));
// @formatter:on
}
@Test
public void validateWhenExpiresAtBeforeNowThenHasErrors() {
this.issuedAt = Instant.now().minus(Duration.ofSeconds(10));
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(5));
this.clockSkew = Duration.ofSeconds(0);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
// @formatter:on
}
@Test
public void validateWhenMissingClaimsThenHasErrors() {
this.claims.remove(IdTokenClaimNames.SUB);
this.claims.remove(IdTokenClaimNames.AUD);
this.issuedAt = null;
this.expiresAt = null;
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.contains(IdTokenClaimNames.SUB))
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD))
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT))
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
// @formatter:on
}
@Test
public void validateFormatError() {
this.claims.remove(IdTokenClaimNames.SUB);
this.claims.remove(IdTokenClaimNames.AUD);
// @formatter:off
assertThat(this.validateIdToken())
.hasSize(1)
.extracting(OAuth2Error::getDescription)
.allMatch((msg) -> msg.equals("The ID Token contains invalid claims: {sub=null, aud=null}"));
// @formatter:on
}
private Collection<OAuth2Error> validateIdToken() {
// @formatter:off
Jwt idToken = Jwt.withTokenValue("token")
.issuedAt(this.issuedAt)
.expiresAt(this.expiresAt)
.headers((h) -> h.putAll(this.headers))
.claims((c) -> c.putAll(this.claims))
.build();
// @formatter:on
OidcIdTokenValidator validator = new OidcIdTokenValidator(this.registration.build());
validator.setClockSkew(this.clockSkew);
return validator.validate(idToken).getErrors();
}
}
| 10,705 | 31.840491 | 97 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationTokenTests.java | /*
* Copyright 2002-2017 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.client.authentication;
import java.util.Collection;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import org.springframework.security.oauth2.core.user.OAuth2User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2LoginAuthenticationToken}.
*
* @author Joe Grandja
*/
public class OAuth2LoginAuthenticationTokenTests {
private OAuth2User principal;
private Collection<? extends GrantedAuthority> authorities;
private ClientRegistration clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessToken accessToken;
@BeforeEach
public void setUp() {
this.principal = mock(OAuth2User.class);
this.authorities = Collections.emptyList();
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizationExchange = new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(),
TestOAuth2AuthorizationResponses.success().code("code").build());
this.accessToken = TestOAuth2AccessTokens.noScopes();
}
@Test
public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(null, this.authorizationExchange));
}
@Test
public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null));
}
@Test
public void constructorAuthorizationRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
OAuth2LoginAuthenticationToken authentication = new OAuth2LoginAuthenticationToken(this.clientRegistration,
this.authorizationExchange);
assertThat(authentication.getPrincipal()).isNull();
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isNull();
assertThat(authentication.isAuthenticated()).isEqualTo(false);
}
@Test
public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2LoginAuthenticationToken(null,
this.authorizationExchange, this.principal, this.authorities, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null, this.principal,
this.authorities, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration,
this.authorizationExchange, null, this.authorities, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAuthoritiesIsNullThenCreated() {
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange, this.principal, null,
this.accessToken);
}
@Test
public void constructorTokenRequestResponseWhenAuthoritiesIsEmptyThenCreated() {
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange, this.principal,
Collections.emptyList(), this.accessToken);
}
@Test
public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration,
this.authorizationExchange, this.principal, this.authorities, null));
}
@Test
public void constructorTokenRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
OAuth2LoginAuthenticationToken authentication = new OAuth2LoginAuthenticationToken(this.clientRegistration,
this.authorizationExchange, this.principal, this.authorities, this.accessToken);
assertThat(authentication.getPrincipal()).isEqualTo(this.principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(this.authorities);
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(this.accessToken);
assertThat(authentication.isAuthenticated()).isEqualTo(true);
}
}
| 6,367 | 43.222222 | 120 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java | /*
* Copyright 2002-2018 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.client.authentication;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationCodeAuthenticationTokenTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessToken accessToken;
@BeforeEach
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizationExchange = new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(),
TestOAuth2AuthorizationResponses.success().code("code").build());
this.accessToken = TestOAuth2AccessTokens.noScopes();
}
@Test
public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange));
}
@Test
public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null));
}
@Test
public void constructorAuthorizationRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
this.clientRegistration, this.authorizationExchange);
assertThat(authentication.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
assertThat(authentication.getCredentials())
.isEqualTo(this.authorizationExchange.getAuthorizationResponse().getCode());
assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isNull();
assertThat(authentication.isAuthenticated()).isEqualTo(false);
}
@Test
public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null,
this.authorizationExchange, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
this.authorizationExchange, null));
}
@Test
public void constructorTokenRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
this.clientRegistration, this.authorizationExchange, this.accessToken);
assertThat(authentication.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
assertThat(authentication.getCredentials()).isEqualTo(this.accessToken.getTokenValue());
assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(this.accessToken);
assertThat(authentication.isAuthenticated()).isEqualTo(true);
}
}
| 5,364 | 45.652174 | 120 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/TestOAuth2AuthorizationCodeAuthenticationTokens.java | /*
* Copyright 2002-2018 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.client.authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges;
/**
* @author Rob Winch
* @since 5.1
*/
public final class TestOAuth2AuthorizationCodeAuthenticationTokens {
private TestOAuth2AuthorizationCodeAuthenticationTokens() {
}
public static OAuth2AuthorizationCodeAuthenticationToken unauthenticated() {
ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange);
}
public static OAuth2AuthorizationCodeAuthenticationToken authenticated() {
ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange, accessToken, refreshToken);
}
}
| 2,346 | 44.134615 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java | /*
* Copyright 2002-2019 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.client.authentication;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private OAuth2AuthorizationCodeReactiveAuthenticationManager manager;
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
private OAuth2AuthorizationRequest.Builder authorizationRequest = TestOAuth2AuthorizationRequests.request();
private OAuth2AuthorizationResponse.Builder authorizationResponse = TestOAuth2AuthorizationResponses.success();
private OAuth2AccessTokenResponse.Builder tokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse();
@BeforeEach
public void setup() {
this.manager = new OAuth2AuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient);
}
@Test
public void authenticateWhenErrorThenOAuth2AuthorizationException() {
this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
}
@Test
public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
this.authorizationRequest.state("notequal");
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
}
@Test
public void authenticateWhenValidThenSuccess() {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(this.tokenResponse.build()));
OAuth2AuthorizationCodeAuthenticationToken result = authenticate();
assertThat(result).isNotNull();
}
@Test
public void authenticateWhenEmptyThenEmpty() {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.empty());
OAuth2AuthorizationCodeAuthenticationToken result = authenticate();
assertThat(result).isNull();
}
@Test
public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
given(this.accessTokenResponseClient.getTokenResponse(any()))
.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
}
private OAuth2AuthorizationCodeAuthenticationToken authenticate() {
OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(this.authorizationRequest.build(),
this.authorizationResponse.build());
OAuth2AuthorizationCodeAuthenticationToken token = new OAuth2AuthorizationCodeAuthenticationToken(
this.registration.build(), exchange);
return (OAuth2AuthorizationCodeAuthenticationToken) this.manager.authenticate(token).block();
}
}
| 5,042 | 44.026786 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java | /*
* Copyright 2002-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.client.authentication;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationCodeAuthenticationProviderTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizationRequest authorizationRequest;
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private OAuth2AuthorizationCodeAuthenticationProvider authenticationProvider;
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient);
}
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null));
}
@Test
public void supportsWhenTypeOAuth2AuthorizationCodeAuthenticationTokenThenReturnTrue() {
assertThat(this.authenticationProvider.supports(OAuth2AuthorizationCodeAuthenticationToken.class)).isTrue();
}
@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthorizationException() {
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
}
@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthorizationException() {
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test
public void authenticateWhenAuthorizationSuccessResponseThenExchangedForAccessToken() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
TestOAuth2AuthorizationResponses.success().build());
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider
.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThat(authenticationResult.isAuthenticated()).isTrue();
assertThat(authenticationResult.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
assertThat(authenticationResult.getCredentials())
.isEqualTo(accessTokenResponse.getAccessToken().getTokenValue());
assertThat(authenticationResult.getAuthorities()).isEqualTo(Collections.emptyList());
assertThat(authenticationResult.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authenticationResult.getAuthorizationExchange()).isEqualTo(authorizationExchange);
assertThat(authenticationResult.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authenticationResult.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
// gh-5368
@Test
public void authenticateWhenAuthorizationSuccessResponseThenAdditionalParametersIncluded() {
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.additionalParameters(additionalParameters).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
TestOAuth2AuthorizationResponses.success().build());
OAuth2AuthorizationCodeAuthenticationToken authentication = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider
.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThat(authentication.getAdditionalParameters())
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
}
| 7,653 | 51.786207 | 140 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java | /*
* Copyright 2002-2019 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.client.authentication;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import org.springframework.security.oauth2.core.user.OAuth2User;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2LoginAuthenticationProvider}.
*
* @author Joe Grandja
*/
public class OAuth2LoginAuthenticationProviderTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizationRequest authorizationRequest;
private OAuth2AuthorizationResponse authorizationResponse;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
private OAuth2LoginAuthenticationProvider authenticationProvider;
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("scope1", "scope2").build();
this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build();
this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
this.authorizationResponse);
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.userService = mock(OAuth2UserService.class);
this.authenticationProvider = new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient,
this.userService);
}
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(null, this.userService));
}
@Test
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setAuthoritiesMapper(null));
}
@Test
public void supportsWhenTypeOAuth2LoginAuthenticationTokenThenReturnTrue() {
assertThat(this.authenticationProvider.supports(OAuth2LoginAuthenticationToken.class)).isTrue();
}
@Test
public void authenticateWhenAuthorizationRequestContainsOpenidScopeThenReturnNull() {
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("openid")
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
this.authorizationResponse);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThat(authentication).isNull();
}
@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
}
@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getPrincipal()).isEqualTo(principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(authorities);
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authentication.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
private OAuth2AccessTokenResponse accessTokenSuccessResponse() {
Instant expiresAt = Instant.now().plusSeconds(5);
Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2"));
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
// @formatter:off
return OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(expiresAt.getEpochSecond())
.scopes(scopes)
.refreshToken("refresh-token-1234")
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
}
| 11,571 | 50.660714 | 130 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java | /*
* Copyright 2002-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.client.authentication;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2LoginReactiveAuthenticationManagerTests {
@Mock
private ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
@Mock
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
OAuth2AuthorizationResponse.Builder authorizationResponseBldr = OAuth2AuthorizationResponse.success("code")
.state("state");
private OAuth2LoginReactiveAuthenticationManager manager;
@BeforeEach
public void setup() {
this.manager = new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService);
}
@Test
public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
this.accessTokenResponseClient = null;
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
}
@Test
public void constructorWhenNullUserServiceThenIllegalArgumentException() {
this.userService = null;
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
}
@Test
public void authenticateWhenNoSubscriptionThenDoesNothing() {
// we didn't do anything because it should cause a ClassCastException (as verified
// below)
TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
this.manager.authenticate(token);
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test
@Disabled
public void authenticationWhenOidcThenEmpty() {
this.registration.scope("openid");
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
}
@Test
public void authenticationWhenErrorThenOAuth2AuthenticationException() {
// @formatter:off
this.authorizationResponseBldr = OAuth2AuthorizationResponse
.error("error")
.state("state");
// @formatter:on
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
this.authorizationResponseBldr.state("notmatch");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticationWhenOAuth2UserNotFoundThenEmpty() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.userService.loadUser(any())).willReturn(Mono.empty());
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
}
@Test
public void authenticationWhenOAuth2UserFoundThenSuccess() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken())
.block();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
assertThat(result.isAuthenticated()).isTrue();
}
// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
this.manager.authenticate(loginToken()).block();
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.manager.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken())
.block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
private OAuth2AuthorizationCodeAuthenticationToken loginToken() {
ClientRegistration clientRegistration = this.registration.build();
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().state("state")
.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr
.redirectUri(clientRegistration.getRedirectUri()).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, authorizationExchange);
}
}
| 10,469 | 47.248848 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/TestOAuth2AuthenticationTokens.java | /*
* Copyright 2002-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.client.authentication;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.TestOAuth2Users;
/**
* @author Josh Cummings
* @since 5.2
*/
public final class TestOAuth2AuthenticationTokens {
private TestOAuth2AuthenticationTokens() {
}
public static OAuth2AuthenticationToken authenticated() {
DefaultOAuth2User principal = TestOAuth2Users.create();
String registrationId = "registration-id";
return new OAuth2AuthenticationToken(principal, principal.getAuthorities(), registrationId);
}
public static OAuth2AuthenticationToken oidcAuthenticated() {
DefaultOidcUser principal = TestOidcUsers.create();
String registrationId = "registration-id";
return new OAuth2AuthenticationToken(principal, principal.getAuthorities(), registrationId);
}
}
| 1,654 | 34.978261 | 94 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthenticationTokenTests.java | /*
* Copyright 2002-2017 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.client.authentication;
import java.util.Collection;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2AuthenticationToken}.
*
* @author Joe Grandja
*/
public class OAuth2AuthenticationTokenTests {
private OAuth2User principal;
private Collection<? extends GrantedAuthority> authorities;
private String authorizedClientRegistrationId;
@BeforeEach
public void setUp() {
this.principal = mock(OAuth2User.class);
this.authorities = Collections.emptyList();
this.authorizedClientRegistrationId = "client-registration-1";
}
@Test
public void constructorWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2AuthenticationToken(null, this.authorities, this.authorizedClientRegistrationId));
}
@Test
public void constructorWhenAuthoritiesIsNullThenCreated() {
new OAuth2AuthenticationToken(this.principal, null, this.authorizedClientRegistrationId);
}
@Test
public void constructorWhenAuthoritiesIsEmptyThenCreated() {
new OAuth2AuthenticationToken(this.principal, Collections.emptyList(), this.authorizedClientRegistrationId);
}
@Test
public void constructorWhenAuthorizedClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthenticationToken(this.principal, this.authorities, null));
}
@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(this.principal, this.authorities,
this.authorizedClientRegistrationId);
assertThat(authentication.getPrincipal()).isEqualTo(this.principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(this.authorities);
assertThat(authentication.getAuthorizedClientRegistrationId()).isEqualTo(this.authorizedClientRegistrationId);
assertThat(authentication.isAuthenticated()).isEqualTo(true);
}
}
| 3,061 | 34.604651 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveJwtBearerTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.util.Collections;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.client.WebClient;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link WebClientReactiveJwtBearerTokenResponseClient}.
*
* @author Steve Riesenberg
*/
public class WebClientReactiveJwtBearerTokenResponseClientTests {
// @formatter:off
private static final String DEFAULT_ACCESS_TOKEN_RESPONSE = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": 3600\n"
+ "}\n";
// @formatter:on
private WebClientReactiveJwtBearerTokenResponseClient client;
private MockWebServer server;
private ClientRegistration.Builder clientRegistration;
private Jwt jwtAssertion;
@BeforeEach
public void setup() throws Exception {
this.client = new WebClientReactiveJwtBearerTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.clientCredentials()
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.tokenUri(tokenUri)
.scope("read", "write");
// @formatter:on
this.jwtAssertion = TestJwts.jwt().build();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setWebClientWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setWebClient(null))
.withMessage("webClient cannot be null");
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setBodyExtractorWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setBodyExtractor(null))
.withMessage("bodyExtractor cannot be null");
}
@Test
public void getTokenResponseWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.getTokenResponse(null))
.withMessage("grantRequest cannot be null");
}
@Test
public void getTokenResponseWhenInvalidResponseThenThrowOAuth2AuthorizationException() {
ClientRegistration registration = this.clientRegistration.build();
enqueueUnexpectedResponse();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessage("[invalid_token_response] Empty OAuth 2.0 Access Token Response");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
ClientRegistration registration = this.clientRegistration.build();
enqueueServerErrorResponse();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR))
.withMessageContaining("[server_error]");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"error\": \"invalid_grant\"\n"
+ "}\n";
// @formatter:on
ClientRegistration registration = this.clientRegistration.build();
enqueueJson(accessTokenResponse);
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT))
.withMessageContaining("[invalid_grant]");
}
@Test
public void getTokenResponseWhenResponseIsNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": 3600\n"
+ "}\n";
// @formatter:on
ClientRegistration registration = this.clientRegistration.build();
enqueueJson(accessTokenResponse);
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response] An error occurred parsing the Access Token response")
.withMessageContaining("Unsupported token_type: not-bearer");
}
@Test
public void getTokenResponseWhenWebClientSetThenCalled() {
WebClient customClient = mock(WebClient.class);
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.client.setWebClient(customClient);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
ClientRegistration registration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
this.client.getTokenResponse(request).block();
verify(customClient).post();
}
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.client.setHeadersConverter(headersConverter);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> addedHeadersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.client.addHeadersConverter(addedHeadersConverter);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenParametersConverterAddedThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.client.addParametersConverter(addedParametersConverter);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains(
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer",
"custom-parameter-name=custom-parameter-value");
}
@Test
public void convertWhenParametersConverterSetThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.client.setParametersConverter(parametersConverter);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
@Test
public void getTokenResponseWhenBodyExtractorSetThenCalled() {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = mock(
BodyExtractor.class);
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(bodyExtractor.extract(any(), any())).willReturn(Mono.just(response));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
this.client.setBodyExtractor(bodyExtractor);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
this.client.getTokenResponse(request).block();
verify(bodyExtractor).extract(any(), any());
}
@Test
public void getTokenResponseWhenClientSecretBasicThenSuccess() throws Exception {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": 3600,\n"
+ " \"scope\": \"read write\""
+ "}\n";
// @formatter:on
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
enqueueJson(accessTokenResponse);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
assertThat(response).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("read", "write");
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getBody().readUtf8()).isEqualTo(
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&scope=read+write&assertion=token");
}
@Test
public void getTokenResponseWhenClientSecretPostThenSuccess() throws Exception {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": 3600,\n"
+ " \"scope\": \"read write\""
+ "}\n";
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.build();
// @formatter:on
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
enqueueJson(accessTokenResponse);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
assertThat(response).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("read", "write");
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).isEqualTo(
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&client_id=client-id&client_secret=client-secret&scope=read+write&assertion=token");
}
@Test
public void getTokenResponseWhenResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": 3600,\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
enqueueJson(accessTokenResponse);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
assertThat(response).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenResponseDoesNotIncludeScopeThenReturnAccessTokenResponseWithNoScopes()
throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
assertThat(response).isNotNull();
assertThat(response.getAccessToken().getScopes()).isEmpty();
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.client.getTokenResponse(jwtBearerGrantRequest).block());
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.client.getTokenResponse(jwtBearerGrantRequest).block());
}
private void enqueueJson(String body) {
MockResponse response = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(response);
}
private void enqueueUnexpectedResponse() {
// @formatter:off
MockResponse response = new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(301);
// @formatter:on
this.server.enqueue(response);
}
private void enqueueServerErrorResponse() {
// @formatter:off
MockResponse response = new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(500)
.setBody("{}");
// @formatter:on
this.server.enqueue(response);
}
}
| 18,991 | 44.653846 | 153 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/NimbusJwtClientAuthenticationParametersConverterTests.java | /*
* Copyright 2002-2022 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.client.endpoint;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Collections;
import java.util.UUID;
import java.util.function.Function;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.jwk.RSAKey;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JoseHeaderNames;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.util.MultiValueMap;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link NimbusJwtClientAuthenticationParametersConverter}.
*
* @author Joe Grandja
*/
public class NimbusJwtClientAuthenticationParametersConverterTests {
private Function<ClientRegistration, JWK> jwkResolver;
private NimbusJwtClientAuthenticationParametersConverter<OAuth2ClientCredentialsGrantRequest> converter;
@BeforeEach
public void setup() {
this.jwkResolver = mock(Function.class);
this.converter = new NimbusJwtClientAuthenticationParametersConverter<>(this.jwkResolver);
}
@Test
public void constructorWhenJwkResolverNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusJwtClientAuthenticationParametersConverter<>(null))
.withMessage("jwkResolver cannot be null");
}
@Test
public void convertWhenAuthorizationGrantRequestNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.convert(null))
.withMessage("authorizationGrantRequest cannot be null");
}
@Test
public void setJwtClientAssertionCustomizerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setJwtClientAssertionCustomizer(null))
.withMessage("jwtClientAssertionCustomizer cannot be null");
}
@Test
public void convertWhenOtherClientAuthenticationMethodThenNotCustomized() {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThat(this.converter.convert(clientCredentialsGrantRequest)).isNull();
verifyNoInteractions(this.jwkResolver);
}
@Test
public void convertWhenJwkNotResolvedThenThrowOAuth2AuthorizationException() {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.converter.convert(clientCredentialsGrantRequest))
.withMessage("[invalid_key] Failed to resolve JWK signing key for client registration '"
+ clientRegistration.getRegistrationId() + "'.");
}
@Test
public void convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized() throws Exception {
RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
given(this.jwkResolver.apply(any())).willReturn(rsaJwk);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
assertThat(encodedJws).isNotNull();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience())
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
assertThat(jws.getId()).isNotNull();
assertThat(jws.getIssuedAt()).isNotNull();
assertThat(jws.getExpiresAt()).isNotNull();
}
@Test
public void convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized() {
OctetSequenceKey secretJwk = TestJwks.DEFAULT_SECRET_JWK;
given(this.jwkResolver.apply(any())).willReturn(secretJwk);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
assertThat(encodedJws).isNotNull();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID());
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience())
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
assertThat(jws.getId()).isNotNull();
assertThat(jws.getIssuedAt()).isNotNull();
assertThat(jws.getExpiresAt()).isNotNull();
}
@Test
public void convertWhenJwtClientAssertionCustomizerSetThenUsed() {
OctetSequenceKey secretJwk = TestJwks.DEFAULT_SECRET_JWK;
given(this.jwkResolver.apply(any())).willReturn(secretJwk);
String headerName = "custom-header";
String headerValue = "header-value";
String claimName = "custom-claim";
String claimValue = "claim-value";
this.converter.setJwtClientAssertionCustomizer((context) -> {
context.getHeaders().header(headerName, headerValue);
context.getClaims().claim(claimName, claimValue);
});
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
assertThat(encodedJws).isNotNull();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID());
assertThat(jws.getHeaders().get(headerName)).isEqualTo(headerValue);
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience())
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
assertThat(jws.getId()).isNotNull();
assertThat(jws.getIssuedAt()).isNotNull();
assertThat(jws.getExpiresAt()).isNotNull();
assertThat(jws.getClaimAsString(claimName)).isEqualTo(claimValue);
}
// gh-9814
@Test
public void convertWhenClientKeyChangesThenNewKeyUsed() throws Exception {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
RSAKey rsaJwk1 = TestJwks.DEFAULT_RSA_JWK;
given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk1);
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk1.toRSAPublicKey()).build();
jwtDecoder.decode(encodedJws);
RSAKey rsaJwk2 = generateRsaJwk();
given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk2);
parameters = this.converter.convert(clientCredentialsGrantRequest);
encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk2.toRSAPublicKey()).build();
jwtDecoder.decode(encodedJws);
}
private static RSAKey generateRsaJwk() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// @formatter:off
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
// @formatter:on
}
}
| 12,515 | 43.070423 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java | /*
* Copyright 2002-2022 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.client.endpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2ClientCredentialsGrantRequest}.
*
* @author Joe Grandja
*/
public class OAuth2ClientCredentialsGrantRequestTests {
private ClientRegistration clientRegistration;
@BeforeEach
public void setup() {
// @formatter:off
this.clientRegistration = ClientRegistration.withRegistrationId("registration-1")
.clientId("client-1")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.scope("read", "write")
.tokenUri("https://provider.com/oauth2/token")
.build();
// @formatter:on
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null));
}
@Test
public void constructorWhenValidParametersProvidedThenCreated() {
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThat(clientCredentialsGrantRequest.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(clientCredentialsGrantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
}
}
| 2,437 | 35.939394 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyExtractor;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link WebClientReactiveRefreshTokenTokenResponseClient}.
*
* @author Joe Grandja
*/
public class WebClientReactiveRefreshTokenTokenResponseClientTests {
private WebClientReactiveRefreshTokenTokenResponseClient tokenResponseClient = new WebClientReactiveRefreshTokenTokenResponseClient();
private ClientRegistration.Builder clientRegistrationBuilder;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().tokenUri(tokenUri);
this.accessToken = TestOAuth2AccessTokens.scopes("read", "write");
this.refreshToken = TestOAuth2RefreshTokens.refreshToken();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(refreshTokenGrantRequest).block();
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=refresh_token");
assertThat(formParameters).contains("refresh_token=refresh-token");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes())
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(this.refreshToken.getTokenValue());
}
@Test
public void getTokenResponseWhenClientAuthenticationPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-id");
assertThat(formParameters).contains("client_secret=client-secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2RefreshTokenGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
this.tokenResponseClient.addParametersConverter(jwtClientAuthenticationConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("An error occurred parsing the Access Token response")
.withCauseInstanceOf(Throwable.class);
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken,
Collections.singleton("read"));
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(refreshTokenGrantRequest).block();
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("scope=read");
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenErrorResponse = "{\n"
+ " \"error\": \"unauthorized_client\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {
// @formatter:off
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(json);
// @formatter:on
}
// gh-10130
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> addedHeadersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
// gh-10130
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter1.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter1);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter1).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token",
"custom-parameter-name=custom-parameter-value");
}
@Test
public void convertWhenParametersConverterSetThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
String accessTokenSuccessResponse = "{}";
WebClientReactiveRefreshTokenTokenResponseClient customClient = new WebClientReactiveRefreshTokenTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock(BodyExtractor.class);
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(refreshTokenGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block());
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block());
}
}
| 23,282 | 46.711066 | 173 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.validateMockitoUsage;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
public class WebClientReactiveClientCredentialsTokenResponseClientTests {
private MockWebServer server;
private WebClientReactiveClientCredentialsTokenResponseClient client = new WebClientReactiveClientCredentialsTokenResponseClient();
private ClientRegistration.Builder clientRegistration;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.clientRegistration = TestClientRegistrations.clientCredentials()
.tokenUri(this.server.url("/oauth2/token").uri().toASCIIString());
}
@AfterEach
public void cleanup() throws Exception {
validateMockitoUsage();
this.server.shutdown();
}
@Test
public void getTokenResponseWhenHeaderThenSuccess() throws Exception {
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\",\n"
+ " \"scope\":\"create\"\n"
+ "}");
// @formatter:on
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
RecordedRequest actualRequest = this.server.takeRequest();
String body = actualRequest.getBody().readUtf8();
assertThat(response.getAccessToken()).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("create");
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(body).isEqualTo("grant_type=client_credentials&scope=read%3Auser");
}
// gh-9610
@Test
public void getTokenResponseWhenSpecialCharactersThenSuccessWithEncodedClientCredentials() throws Exception {
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\",\n"
+ " \"scope\":\"create\"\n"
+ "}");
// @formatter:on
String clientCredentialWithAnsiKeyboardSpecialCharacters = "~!@#$%^&*()_+{}|:\"<>?`-=[]\\;',./ ";
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.clientId(clientCredentialWithAnsiKeyboardSpecialCharacters)
.clientSecret(clientCredentialWithAnsiKeyboardSpecialCharacters).build());
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
RecordedRequest actualRequest = this.server.takeRequest();
String body = actualRequest.getBody().readUtf8();
assertThat(response.getAccessToken()).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("create");
String urlEncodedClientCredentialecret = URLEncoder.encode(clientCredentialWithAnsiKeyboardSpecialCharacters,
StandardCharsets.UTF_8.toString());
String clientCredentials = Base64.getEncoder()
.encodeToString((urlEncodedClientCredentialecret + ":" + urlEncodedClientCredentialecret)
.getBytes(StandardCharsets.UTF_8));
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic " + clientCredentials);
assertThat(body).isEqualTo("grant_type=client_credentials&scope=read%3Auser");
}
@Test
public void getTokenResponseWhenPostThenSuccess() throws Exception {
ClientRegistration registration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\",\n"
+ " \"scope\":\"create\"\n"
+ "}");
// @formatter:on
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
RecordedRequest actualRequest = this.server.takeRequest();
String body = actualRequest.getBody().readUtf8();
assertThat(response.getAccessToken()).isNotNull();
assertThat(response.getAccessToken().getScopes()).containsExactly("create");
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(body).isEqualTo(
"grant_type=client_credentials&client_id=client-id&client_secret=client-secret&scope=read%3Auser");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}");
// @formatter:on
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
this.client.getTokenResponse(request).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}");
// @formatter:on
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
this.client.getTokenResponse(request).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2ClientCredentialsGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
this.client.addParametersConverter(jwtClientAuthenticationConverter);
}
@Test
public void getTokenResponseWhenNoScopeThenReturnAccessTokenResponseWithNoScopes() {
ClientRegistration registration = this.clientRegistration.build();
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
assertThat(response.getAccessToken().getScopes()).isEmpty();
}
@Test
public void setWebClientNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setWebClient(null));
}
@Test
public void setWebClientCustomThenCustomClientIsUsed() {
WebClient customClient = mock(WebClient.class);
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.client.setWebClient(customClient);
ClientRegistration registration = this.clientRegistration.build();
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
verify(customClient, atLeastOnce()).post();
}
@Test
public void getTokenResponseWhenInvalidResponse() throws WebClientResponseException {
ClientRegistration registration = this.clientRegistration.build();
enqueueUnexpectedResponse();
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private void enqueueUnexpectedResponse() {
// @formatter:off
MockResponse response = new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(301);
// @formatter:on
this.server.enqueue(response);
}
private void enqueueJson(String body) {
MockResponse response = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(response);
}
// gh-10130
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> addedHeadersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.client.addHeadersConverter(addedHeadersConverter);
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
// gh-10130
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.client.setHeadersConverter(headersConverter);
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.client.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.client.addParametersConverter(addedParametersConverter);
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials",
"custom-parameter-name=custom-parameter-value");
}
@Test
public void convertWhenParametersConverterSetThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.client.setParametersConverter(parametersConverter);
// @formatter:off
enqueueJson("{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}");
// @formatter:on
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
enqueueJson("{}");
WebClientReactiveClientCredentialsTokenResponseClient customClient = new WebClientReactiveClientCredentialsTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock(BodyExtractor.class);
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(request).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.client.getTokenResponse(clientCredentialsGrantRequest).block());
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.client.getTokenResponse(clientCredentialsGrantRequest).block());
}
}
| 21,129 | 43.578059 | 178 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/JwtBearerGrantRequestEntityConverterTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link JwtBearerGrantRequestEntityConverter}.
*
* @author Hassene Laaribi
* @author Joe Grandja
*/
public class JwtBearerGrantRequestEntityConverterTests {
private JwtBearerGrantRequestEntityConverter converter;
@BeforeEach
public void setup() {
this.converter = new JwtBearerGrantRequestEntityConverter();
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
this.converter.convert(jwtBearerGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(JwtBearerGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(JwtBearerGrantRequest.class));
}
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(Converter.class);
this.converter.addParametersConverter(parametersConverter2);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
this.converter.convert(jwtBearerGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(JwtBearerGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(JwtBearerGrantRequest.class));
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
RequestEntity<?> requestEntity = this.converter.convert(jwtBearerGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.ASSERTION)).isEqualTo(jwtAssertion.getTokenValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write");
}
}
| 6,790 | 44.577181 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverterTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2ClientCredentialsGrantRequestEntityConverter}.
*
* @author Joe Grandja
*/
public class OAuth2ClientCredentialsGrantRequestEntityConverterTests {
private OAuth2ClientCredentialsGrantRequestEntityConverter converter;
@BeforeEach
public void setup() {
this.converter = new OAuth2ClientCredentialsGrantRequestEntityConverter();
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
this.converter.convert(clientCredentialsGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(OAuth2ClientCredentialsGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(OAuth2ClientCredentialsGrantRequest.class));
}
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(
Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(
Converter.class);
this.converter.addParametersConverter(parametersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
this.converter.convert(clientCredentialsGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(OAuth2ClientCredentialsGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(OAuth2ClientCredentialsGrantRequest.class));
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
RequestEntity<?> requestEntity = this.converter.convert(clientCredentialsGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).contains(clientRegistration.getScopes());
}
// gh-9610
@SuppressWarnings("unchecked")
@Test
public void convertWhenSpecialCharactersThenConvertsWithEncodedClientCredentials()
throws UnsupportedEncodingException {
String clientCredentialWithAnsiKeyboardSpecialCharacters = "~!@#$%^&*()_+{}|:\"<>?`-=[]\\;',./ ";
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.clientId(clientCredentialWithAnsiKeyboardSpecialCharacters)
.clientSecret(clientCredentialWithAnsiKeyboardSpecialCharacters)
.build();
// @formatter:on
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
RequestEntity<?> requestEntity = this.converter.convert(clientCredentialsGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
String urlEncodedClientCredential = URLEncoder.encode(clientCredentialWithAnsiKeyboardSpecialCharacters,
StandardCharsets.UTF_8.toString());
String clientCredentials = Base64.getEncoder().encodeToString(
(urlEncodedClientCredential + ":" + urlEncodedClientCredential).getBytes(StandardCharsets.UTF_8));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic " + clientCredentials);
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).contains(clientRegistration.getScopes());
}
}
| 8,431 | 48.6 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultJwtBearerTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.net.URLEncoder;
import java.time.Instant;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultJwtBearerTokenResponseClient}.
*
* @author Hassene Laaribi
* @author Joe Grandja
*/
public class DefaultJwtBearerTokenResponseClientTests {
private DefaultJwtBearerTokenResponseClient tokenResponseClient;
private ClientRegistration.Builder clientRegistration;
private Jwt jwtAssertion;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.tokenResponseClient = new DefaultJwtBearerTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.clientCredentials()
.clientId("client-1")
.clientSecret("secret")
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.tokenUri(tokenUri)
.scope("read", "write");
// @formatter:on
this.jwtAssertion = TestJwts.jwt().build();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(jwtBearerGrantRequest);
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("grant_type=" + URLEncoder.encode(AuthorizationGrantType.JWT_BEARER.getValue(), "UTF-8"));
assertThat(formParameters).contains("scope=read+write");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactlyInAnyOrder("read", "write");
assertThat(accessTokenResponse.getRefreshToken()).isNull();
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretBasicThenAuthorizationHeaderIsSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-1");
assertThat(formParameters).contains("client_secret=secret");
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(jwtBearerGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasNoScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(jwtBearerGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"invalid_grant\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
.withMessageContaining("[invalid_grant]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
this.jwtAssertion);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response");
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest));
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest));
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 12,396 | 44.745387 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultAuthorizationCodeTokenResponseClient}.
*
* @author Joe Grandja
*/
public class DefaultAuthorizationCodeTokenResponseClientTests {
private DefaultAuthorizationCodeTokenResponseClient tokenResponseClient;
private ClientRegistration.Builder clientRegistration;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.tokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.clientRegistration()
.clientId("client-1")
.clientSecret("secret")
.redirectUri("https://client.com/callback/client-1")
.tokenUri(tokenUri)
.scope("read", "write");
// @formatter:on
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\",\n"
+ " \"refresh_token\": \"refresh-token-1234\",\n"
+ " \"custom_parameter_1\": \"custom-value-1\",\n"
+ " \"custom_parameter_2\": \"custom-value-2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=authorization_code");
assertThat(formParameters).contains("code=code-1234");
assertThat(formParameters).contains("redirect_uri=https%3A%2F%2Fclient.com%2Fcallback%2Fclient-1");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write");
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234");
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretBasicThenAuthorizationHeaderIsSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration));
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-1");
assertThat(formParameters).contains("client_secret=secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration));
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration));
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
// gh-13143
@Test
public void getTokenResponseWhenTokenEndpointReturnsEmptyBodyThenIllegalArgument() {
this.server.enqueue(new MockResponse().setResponseCode(302));
ClientRegistration clientRegistration = this.clientRegistration.build();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)));
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2AuthorizationCodeGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter = new OAuth2AuthorizationCodeGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(jwtClientAuthenticationConverter);
this.tokenResponseClient.setRequestEntityConverter(requestEntityConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"refresh_token\": \"refresh-token-1234\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasNoScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"refresh_token\": \"refresh-token-1234\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
@Test
public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
ClientRegistration clientRegistration = this.clientRegistration.tokenUri(invalidTokenUri).build();
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@Test
public void getTokenResponseWhenMalformedResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\",\n"
+ " \"refresh_token\": \"refresh-token-1234\",\n"
+ " \"custom_parameter_1\": \"custom-value-1\",\n"
+ " \"custom_parameter_2\": \"custom-value-2\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve "
+ "the OAuth 2.0 Access Token Response");
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest));
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest));
}
private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest(ClientRegistration clientRegistration) {
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.clientId(clientRegistration.getClientId()).state("state-1234")
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success("code-1234")
.state("state-1234").redirectUri(clientRegistration.getRedirectUri()).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authorizationExchange);
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 19,660 | 46.720874 | 178 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java | /*
* Copyright 2002-2019 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.client.endpoint;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2RefreshTokenGrantRequest}.
*
* @author Joe Grandja
*/
public class OAuth2RefreshTokenGrantRequestTests {
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
@BeforeEach
public void setup() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.accessToken = TestOAuth2AccessTokens.scopes("read", "write");
this.refreshToken = TestOAuth2RefreshTokens.refreshToken();
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken))
.withMessage("clientRegistration cannot be null");
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken))
.withMessage("accessToken cannot be null");
}
@Test
public void constructorWhenRefreshTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null))
.withMessage("refreshToken cannot be null");
}
@Test
public void constructorWhenValidParametersProvidedThenCreated() {
Set<String> scopes = new HashSet<>(Arrays.asList("read", "write"));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration, this.accessToken, this.refreshToken, scopes);
assertThat(refreshTokenGrantRequest.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(refreshTokenGrantRequest.getAccessToken()).isSameAs(this.accessToken);
assertThat(refreshTokenGrantRequest.getRefreshToken()).isSameAs(this.refreshToken);
assertThat(refreshTokenGrantRequest.getScopes()).isEqualTo(scopes);
}
}
| 3,488 | 38.202247 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.client.WebClient;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
* @since 5.1
*/
public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
private ClientRegistration.Builder clientRegistration;
private WebClientReactiveAuthorizationCodeTokenResponseClient tokenResponseClient = new WebClientReactiveAuthorizationCodeTokenResponseClient();
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(tokenUri);
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"openid profile\",\n"
+ " \"refresh_token\": \"refresh-token-1234\",\n"
+ " \"custom_parameter_1\": \"custom-value-1\",\n"
+ " \"custom_parameter_2\": \"custom-value-2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest()).block();
String body = this.server.takeRequest().getBody().readUtf8();
assertThat(body).isEqualTo(
"grant_type=authorization_code&code=code&redirect_uri=%7BbaseUrl%7D%2F%7Baction%7D%2Foauth2%2Fcode%2F%7BregistrationId%7D");
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("openid", "profile");
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234");
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=authorization_code",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=authorization_code",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2AuthorizationCodeGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
this.tokenResponseClient.addParametersConverter(jwtClientAuthenticationConverter);
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(
jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("unauthorized_client");
}
// gh-5594
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{}";
this.server.enqueue(
jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.withMessageContaining("server_error");
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ "\"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.withMessageContaining("invalid_token_response");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenReturnAccessTokenResponseUsingResponseScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ "\"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"openid profile\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.clientRegistration.scope("openid", "profile", "email", "address");
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest()).block();
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("openid", "profile");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenReturnAccessTokenResponseWithNoScopes() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.clientRegistration.scope("openid", "profile", "email", "address");
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(authorizationCodeGrantRequest()).block();
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest() {
return authorizationCodeGrantRequest(this.clientRegistration.build());
}
private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest(ClientRegistration registration) {
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.clientId(registration.getClientId()).state("state")
.authorizationUri(registration.getProviderDetails().getAuthorizationUri())
.redirectUri(registration.getRedirectUri()).scopes(registration.getScopes()).build();
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success("code").state("state")
.redirectUri(registration.getRedirectUri()).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2AuthorizationCodeGrantRequest(registration, authorizationExchange);
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
@Test
public void setWebClientNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
}
@Test
public void setCustomWebClientThenCustomWebClientIsUsed() {
WebClient customClient = mock(WebClient.class);
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.tokenResponseClient.setWebClient(customClient);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"openid profile\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.clientRegistration.scope("openid", "profile", "email", "address");
OAuth2AccessTokenResponse response = this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest())
.block();
verify(customClient, atLeastOnce()).post();
}
@Test
public void getTokenResponseWhenOAuth2AuthorizationRequestContainsPkceParametersThenTokenRequestBodyShouldContainCodeVerifier()
throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(pkceAuthorizationCodeGrantRequest()).block();
String body = this.server.takeRequest().getBody().readUtf8();
assertThat(body).isEqualTo(
"grant_type=authorization_code&client_id=client-id&code=code&redirect_uri=%7BbaseUrl%7D%2F%7Baction%7D%2Foauth2%2Fcode%2F%7BregistrationId%7D&code_verifier=code-verifier-1234");
}
private OAuth2AuthorizationCodeGrantRequest pkceAuthorizationCodeGrantRequest() {
ClientRegistration registration = this.clientRegistration.clientAuthenticationMethod(null).clientSecret(null)
.build();
Map<String, Object> attributes = new HashMap<>();
attributes.put(PkceParameterNames.CODE_VERIFIER, "code-verifier-1234");
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge-1234");
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.clientId(registration.getClientId())
.state("state")
.authorizationUri(registration.getProviderDetails().getAuthorizationUri())
.redirectUri(registration.getRedirectUri())
.scopes(registration.getScopes())
.attributes(attributes)
.additionalParameters(additionalParameters)
.build();
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse
.success("code")
.state("state")
.redirectUri(registration.getRedirectUri())
.build();
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
return new OAuth2AuthorizationCodeGrantRequest(registration, authorizationExchange);
}
// gh-10130
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> addedHeadersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"openid profile\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
// gh-10130
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"openid profile\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=authorization_code",
"custom-parameter-name=custom-parameter-value");
}
@Test
public void convertWhenParametersConverterSetThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
String accessTokenSuccessResponse = "{}";
WebClientReactiveAuthorizationCodeTokenResponseClient customClient = new WebClientReactiveAuthorizationCodeTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock(BodyExtractor.class);
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(authorizationCodeGrantRequest())
.block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest).block());
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest).block());
}
}
| 24,722 | 46.001901 | 181 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/JwtBearerGrantRequestTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link JwtBearerGrantRequest}.
*
* @author Hassene Laaribi
*/
public class JwtBearerGrantRequestTests {
private final ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER).build();
private final Jwt jwtAssertion = TestJwts.jwt().build();
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new JwtBearerGrantRequest(null, this.jwtAssertion))
.withMessage("clientRegistration cannot be null");
}
@Test
public void constructorWhenJwtIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new JwtBearerGrantRequest(this.clientRegistration, null))
.withMessage("jwt cannot be null");
}
@Test
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
assertThatIllegalArgumentException()
.isThrownBy(() -> new JwtBearerGrantRequest(registration, this.jwtAssertion))
.withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
}
@Test
public void constructorWhenValidParametersProvidedThenCreated() {
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration,
this.jwtAssertion);
assertThat(jwtBearerGrantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.JWT_BEARER);
assertThat(jwtBearerGrantRequest.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(jwtBearerGrantRequest.getJwt()).isSameAs(this.jwtAssertion);
}
}
| 2,970 | 40.263889 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverterTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2AuthorizationCodeGrantRequestEntityConverter}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationCodeGrantRequestEntityConverterTests {
private OAuth2AuthorizationCodeGrantRequestEntityConverter converter;
@BeforeEach
public void setup() {
this.converter = new OAuth2AuthorizationCodeGrantRequestEntityConverter();
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationExchange authorizationExchange = TestOAuth2AuthorizationExchanges.success();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(
clientRegistration, authorizationExchange);
this.converter.convert(authorizationCodeGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(OAuth2AuthorizationCodeGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(OAuth2AuthorizationCodeGrantRequest.class));
}
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(
Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(
Converter.class);
this.converter.addParametersConverter(parametersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationExchange authorizationExchange = TestOAuth2AuthorizationExchanges.success();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(
clientRegistration, authorizationExchange);
this.converter.convert(authorizationCodeGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(OAuth2AuthorizationCodeGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(OAuth2AuthorizationCodeGrantRequest.class));
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationExchange authorizationExchange = TestOAuth2AuthorizationExchanges.success();
OAuth2AuthorizationRequest authorizationRequest = authorizationExchange.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authorizationExchange.getAuthorizationResponse();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(
clientRegistration, authorizationExchange);
RequestEntity<?> requestEntity = this.converter.convert(authorizationCodeGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.CODE)).isEqualTo(authorizationResponse.getCode());
assertThat(formParameters.getFirst(OAuth2ParameterNames.CLIENT_ID)).isNull();
assertThat(formParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI))
.isEqualTo(authorizationRequest.getRedirectUri());
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenPkceGrantRequestValidThenConverts() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.clientAuthenticationMethod(null).clientSecret(null).build();
Map<String, Object> attributes = new HashMap<>();
attributes.put(PkceParameterNames.CODE_VERIFIER, "code-verifier-1234");
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge-1234");
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).additionalParameters(additionalParameters).build();
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
authorizationResponse);
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(
clientRegistration, authorizationExchange);
RequestEntity<?> requestEntity = this.converter.convert(authorizationCodeGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).isNull();
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.CODE)).isEqualTo(authorizationResponse.getCode());
assertThat(formParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI))
.isEqualTo(authorizationRequest.getRedirectUri());
assertThat(formParameters.getFirst(OAuth2ParameterNames.CLIENT_ID))
.isEqualTo(authorizationRequest.getClientId());
assertThat(formParameters.getFirst(PkceParameterNames.CODE_VERIFIER))
.isEqualTo(authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER));
}
}
| 10,283 | 53.702128 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverterTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2PasswordGrantRequestEntityConverter}.
*
* @author Joe Grandja
*/
public class OAuth2PasswordGrantRequestEntityConverterTests {
private OAuth2PasswordGrantRequestEntityConverter converter;
@BeforeEach
public void setup() {
this.converter = new OAuth2PasswordGrantRequestEntityConverter();
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.password().build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, "user1",
"password");
this.converter.convert(passwordGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(OAuth2PasswordGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(OAuth2PasswordGrantRequest.class));
}
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(
Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(
Converter.class);
this.converter.addParametersConverter(parametersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.password().build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, "user1",
"password");
this.converter.convert(passwordGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(OAuth2PasswordGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(OAuth2PasswordGrantRequest.class));
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
ClientRegistration clientRegistration = TestClientRegistrations.password().build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, "user1",
"password");
RequestEntity<?> requestEntity = this.converter.convert(passwordGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.PASSWORD.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.USERNAME)).isEqualTo("user1");
assertThat(formParameters.getFirst(OAuth2ParameterNames.PASSWORD)).isEqualTo("password");
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).contains(clientRegistration.getScopes());
}
}
| 6,271 | 45.80597 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultClientCredentialsTokenResponseClient}.
*
* @author Joe Grandja
*/
public class DefaultClientCredentialsTokenResponseClientTests {
private DefaultClientCredentialsTokenResponseClient tokenResponseClient;
private ClientRegistration.Builder clientRegistration;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.tokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.clientCredentials()
.clientId("client-1")
.clientSecret("secret")
.tokenUri(tokenUri)
.scope("read", "write");
// @formatter:on
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
// @formatter:on
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
// @formatter:on
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\",\n"
+ " \"custom_parameter_1\": \"custom-value-1\",\n"
+ " \"custom_parameter_2\": \"custom-value-2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(clientCredentialsGrantRequest);
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=client_credentials");
assertThat(formParameters).contains("scope=read+write");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write");
assertThat(accessTokenResponse.getRefreshToken()).isNull();
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretBasicThenAuthorizationHeaderIsSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-1");
assertThat(formParameters).contains("client_secret=secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2ClientCredentialsGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter = new OAuth2ClientCredentialsGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(jwtClientAuthenticationConverter);
this.tokenResponseClient.setRequestEntityConverter(requestEntityConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(clientCredentialsGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasNoScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(clientCredentialsGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
@Test
public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
ClientRegistration clientRegistration = this.clientRegistration.tokenUri(invalidTokenUri).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@Test
public void getTokenResponseWhenMalformedResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\",\n"
+ " \"custom_parameter_1\": \"custom-value-1\",\n"
+ " \"custom_parameter_2\": \"custom-value-2\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenErrorResponse = "{\n"
+ " \"error\": \"unauthorized_client\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration.build());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest));
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest));
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 19,246 | 46.05868 | 178 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverterTests.java | /*
* Copyright 2002-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.oauth2.client.endpoint;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OAuth2RefreshTokenGrantRequestEntityConverter}.
*
* @author Joe Grandja
*/
public class OAuth2RefreshTokenGrantRequestEntityConverterTests {
private OAuth2RefreshTokenGrantRequestEntityConverter converter;
@BeforeEach
public void setup() {
this.converter = new OAuth2RefreshTokenGrantRequestEntityConverter();
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("read", "write");
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
accessToken, refreshToken);
this.converter.convert(refreshTokenGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(OAuth2RefreshTokenGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(OAuth2RefreshTokenGrantRequest.class));
}
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(
Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(
Converter.class);
this.converter.addParametersConverter(parametersConverter2);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("read", "write");
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
accessToken, refreshToken);
this.converter.convert(refreshTokenGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(OAuth2RefreshTokenGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(OAuth2RefreshTokenGrantRequest.class));
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("read", "write");
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
accessToken, refreshToken, Collections.singleton("read"));
RequestEntity<?> requestEntity = this.converter.convert(refreshTokenGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
.isEqualTo(AuthorizationGrantType.REFRESH_TOKEN.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.REFRESH_TOKEN)).isEqualTo(refreshToken.getTokenValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read");
}
}
| 7,147 | 48.296552 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java | /*
* Copyright 2002-2022 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyExtractor;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link WebClientReactivePasswordTokenResponseClient}.
*
* @author Joe Grandja
*/
public class WebClientReactivePasswordTokenResponseClientTests {
private WebClientReactivePasswordTokenResponseClient tokenResponseClient = new WebClientReactivePasswordTokenResponseClient();
private ClientRegistration.Builder clientRegistrationBuilder;
private String username = "user1";
private String password = "password";
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistrationBuilder = TestClientRegistrations.password().tokenUri(tokenUri);
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenReturnAccessTokenResponseWithNoScope()
throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest)
.block();
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=password");
assertThat(formParameters).contains("username=user1");
assertThat(formParameters).contains("password=password");
assertThat(formParameters).contains("scope=read+write");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
assertThat(accessTokenResponse.getRefreshToken()).isNull();
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest)
.block();
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=password");
assertThat(formParameters).contains("username=user1");
assertThat(formParameters).contains("password=password");
assertThat(formParameters).contains("scope=read+write");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes())
.containsExactly(clientRegistration.getScopes().toArray(new String[0]));
assertThat(accessTokenResponse.getRefreshToken()).isNull();
}
@Test
public void getTokenResponseWhenClientAuthenticationPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block();
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-id");
assertThat(formParameters).contains("client_secret=client-secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=password",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block();
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=password",
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer",
"client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2PasswordGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
this.tokenResponseClient.addParametersConverter(jwtClientAuthenticationConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("An error occurred parsing the Access Token response")
.withCauseInstanceOf(Throwable.class);
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest)
.block();
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("scope=read");
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenErrorResponse = "{\n"
+ " \"error\": \"unauthorized_client\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {
// @formatter:off
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(json);
// @formatter:on
}
// gh-10130
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
}
// gh-10130
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(),
this.username, this.password);
Converter<OAuth2PasswordGrantRequest, HttpHeaders> addedHeadersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
// gh-10130
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(),
this.username, this.password);
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock(Converter.class);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
}
@Test
public void convertWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(),
this.username, this.password);
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=password",
"custom-parameter-name=custom-parameter-value");
}
@Test
public void convertWhenParametersConverterSetThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(),
this.username, this.password);
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(
Converter.class);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
+ " \"token_type\":\"bearer\",\n"
+ " \"expires_in\":3600,\n"
+ " \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
+ "}";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
String accessTokenSuccessResponse = "{}";
WebClientReactivePasswordTokenResponseClient customClient = new WebClientReactivePasswordTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock(BodyExtractor.class);
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(passwordGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
}
| 23,677 | 46.261477 | 169 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java | /*
* Copyright 2002-2022 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultPasswordTokenResponseClient}.
*
* @author Joe Grandja
*/
public class DefaultPasswordTokenResponseClientTests {
private DefaultPasswordTokenResponseClient tokenResponseClient;
private ClientRegistration.Builder clientRegistration;
private String username = "user1";
private String password = "password";
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.tokenResponseClient = new DefaultPasswordTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.password()
.scope("read", "write")
.tokenUri(tokenUri);
// @formatter:on
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=password");
assertThat(formParameters).contains("username=user1");
assertThat(formParameters).contains("password=password");
assertThat(formParameters).contains("scope=read+write");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes())
.containsExactly(clientRegistration.getScopes().toArray(new String[0]));
assertThat(accessTokenResponse.getRefreshToken()).isNull();
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-id");
assertThat(formParameters).contains("client_secret=client-secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
this.username, this.password);
this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2PasswordGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
OAuth2PasswordGrantRequestEntityConverter requestEntityConverter = new OAuth2PasswordGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(jwtClientAuthenticationConverter);
this.tokenResponseClient.setRequestEntityConverter(requestEntityConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistration.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistration.build(), this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("scope=read");
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasNoScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistration.build(), this.username, this.password);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistration.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistration.build(), this.username, this.password);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 14,536 | 45.003165 | 169 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java | /*
* Copyright 2002-2019 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.client.endpoint;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2PasswordGrantRequest}.
*
* @author Joe Grandja
*/
public class OAuth2PasswordGrantRequestTests {
private ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.authorizationGrantType(AuthorizationGrantType.PASSWORD).build();
private String username = "user1";
private String password = "password";
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(null, this.username, this.password))
.withMessage("clientRegistration cannot be null");
}
@Test
public void constructorWhenUsernameIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, null, this.password))
.withMessage("username cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, "", this.password))
.withMessage("username cannot be empty");
}
@Test
public void constructorWhenPasswordIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, null))
.withMessage("password cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, ""))
.withMessage("password cannot be empty");
}
@Test
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(registration, this.username, this.password))
.withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD");
}
@Test
public void constructorWhenValidParametersProvidedThenCreated() {
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(this.clientRegistration,
this.username, this.password);
assertThat(passwordGrantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.PASSWORD);
assertThat(passwordGrantRequest.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(passwordGrantRequest.getUsername()).isEqualTo(this.username);
assertThat(passwordGrantRequest.getPassword()).isEqualTo(this.password);
}
}
| 3,684 | 40.875 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestTests.java | /*
* Copyright 2002-2017 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.client.endpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizationCodeGrantRequest}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationCodeGrantRequestTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
@BeforeEach
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizationExchange = TestOAuth2AuthorizationExchanges.success();
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantRequest(null, this.authorizationExchange));
}
@Test
public void constructorWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantRequest(this.clientRegistration, null));
}
@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistration, this.authorizationExchange);
assertThat(authorizationCodeGrantRequest.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationCodeGrantRequest.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authorizationCodeGrantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
}
}
| 2,838 | 39.557143 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java | /*
* Copyright 2002-2023 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.client.endpoint;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import com.nimbusds.jose.jwk.JWK;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultRefreshTokenTokenResponseClient}.
*
* @author Joe Grandja
*/
public class DefaultRefreshTokenTokenResponseClientTests {
private DefaultRefreshTokenTokenResponseClient tokenResponseClient;
private ClientRegistration.Builder clientRegistration;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.tokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(tokenUri);
this.accessToken = TestOAuth2AccessTokens.scopes("read", "write");
this.refreshToken = TestOAuth2RefreshTokens.refreshToken();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration.build(), this.accessToken, this.refreshToken);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(refreshTokenGrantRequest);
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=refresh_token");
assertThat(formParameters).contains("refresh_token=refresh-token");
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes())
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(this.refreshToken.getTokenValue());
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasOriginalScope() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(refreshTokenGrantRequest);
assertThat(accessTokenResponse.getAccessToken().getScopes())
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("client_id=client-id");
assertThat(formParameters).contains("client_secret=client-secret");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY)
.build();
// @formatter:on
// Configure Jwt client authentication converter
SecretKeySpec secretKey = new SecretKeySpec(
clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
JWK jwk = TestJwks.jwk(secretKey).build();
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
// Configure Jwt client authentication converter
JWK jwk = TestJwks.DEFAULT_RSA_JWK;
Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
configureJwtClientAuthenticationConverter(jwkResolver);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters)
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
assertThat(formParameters).contains("client_assertion=");
}
private void configureJwtClientAuthenticationConverter(Function<ClientRegistration, JWK> jwkResolver) {
NimbusJwtClientAuthenticationParametersConverter<OAuth2RefreshTokenGrantRequest> jwtClientAuthenticationConverter = new NimbusJwtClientAuthenticationParametersConverter<>(
jwkResolver);
OAuth2RefreshTokenGrantRequestEntityConverter requestEntityConverter = new OAuth2RefreshTokenGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(jwtClientAuthenticationConverter);
this.tokenResponseClient.setRequestEntityConverter(requestEntityConverter);
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
// @formatter:off
String accessTokenSuccessResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration.build(), this.accessToken, this.refreshToken, Collections.singleton("read"));
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
.getTokenResponse(refreshTokenGrantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("scope=read");
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistration.build(), this.accessToken, this.refreshToken);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response");
}
// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest));
}
// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest));
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 16,452 | 46.96793 | 173 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java | /*
* Copyright 2002-2022 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.client.http;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link OAuth2ErrorResponseErrorHandler}.
*
* @author Joe Grandja
*/
public class OAuth2ErrorResponseErrorHandlerTests {
private OAuth2ErrorResponseErrorHandler errorHandler = new OAuth2ErrorResponseErrorHandler();
@Test
public void handleErrorWhenErrorResponseBodyThenHandled() {
// @formatter:off
String errorResponse = "{\n"
+ " \"error\": \"unauthorized_client\",\n"
+ " \"error_description\": \"The client is not authorized\"\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("[unauthorized_client] The client is not authorized");
}
@Test
public void handleErrorWhenOAuth2ErrorConverterSetThenCalled() throws IOException {
HttpMessageConverter<OAuth2Error> oauth2ErrorConverter = mock(HttpMessageConverter.class);
this.errorHandler.setErrorConverter(oauth2ErrorConverter);
// @formatter:off
String errorResponse = "{\n"
+ " \"errorCode\": \"unauthorized_client\",\n"
+ " \"errorSummary\": \"The client is not authorized\"\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
given(oauth2ErrorConverter.read(any(), any()))
.willReturn(new OAuth2Error("unauthorized_client", "The client is not authorized", null));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("[unauthorized_client] The client is not authorized");
verify(oauth2ErrorConverter).read(eq(OAuth2Error.class), eq(response));
}
@Test
public void handleErrorWhenErrorResponseWwwAuthenticateHeaderThenHandled() {
String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.BAD_REQUEST);
response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("[insufficient_scope] The access token expired");
}
@Test
public void handleErrorWhenErrorResponseWithInvalidWwwAuthenticateHeaderThenHandled() {
String invalidWwwAuthenticateHeader = "Unauthorized";
MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.BAD_REQUEST);
response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, invalidWwwAuthenticateHeader);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response)).withMessage("[server_error] ");
}
@Test
public void handleErrorWhenErrorResponseWithInvalidStatusCodeThenHandled() {
CustomMockClientHttpResponse response = new CustomMockClientHttpResponse(new byte[0], 596);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("No matching constant for [596]");
}
private static final class CustomMockClientHttpResponse extends MockHttpInputMessage implements ClientHttpResponse {
private final int statusCode;
private CustomMockClientHttpResponse(byte[] content, int statusCode) {
super(content);
this.statusCode = statusCode;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.valueOf(getRawStatusCode());
}
@Override
public int getRawStatusCode() {
return this.statusCode;
}
@Override
public String getStatusText() throws IOException {
HttpStatus httpStatus = HttpStatus.resolve(this.statusCode);
return (httpStatus != null) ? httpStatus.getReasonPhrase() : "";
}
@Override
public void close() {
try {
getBody().close();
}
catch (IOException ex) {
// ignore
}
}
}
}
| 5,611 | 37.176871 | 139 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizationSuccessHandler.java | /*
* Copyright 2002-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.client;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
/**
* Handles when an OAuth 2.0 Client has been successfully authorized (or re-authorized)
* via the authorization server.
*
* @author Phil Clay
* @since 5.3
*/
@FunctionalInterface
public interface ReactiveOAuth2AuthorizationSuccessHandler {
/**
* Called when an OAuth 2.0 Client has been successfully authorized (or re-authorized)
* via the authorization server.
* @param authorizedClient the client that was successfully authorized
* @param principal the {@code Principal} associated with the authorized client
* @param attributes an immutable {@code Map} of extra optional attributes present
* under certain conditions. For example, this might contain a
* {@link org.springframework.web.server.ServerWebExchange ServerWebExchange} if the
* authorization was performed within the context of a {@code ServerWebExchange}.
* @return an empty {@link Mono} that completes after this handler has finished
* handling the event.
*/
Mono<Void> onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
Map<String, Object> attributes);
}
| 1,892 | 36.117647 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
/**
* A strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. Implementations
* will typically implement a specific {@link AuthorizationGrantType authorization grant}
* type.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizationContext
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section
* 1.3 Authorization Grant</a>
*/
@FunctionalInterface
public interface OAuth2AuthorizedClientProvider {
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* context. Implementations must return {@code null} if authorization is not supported
* for the specified client, e.g. the provider doesn't support the
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant} type
* configured for the client.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
* supported for the specified client
*/
@Nullable
OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context);
}
| 2,078 | 38.226415 | 89 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientService.java | /*
* Copyright 2002-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.client;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.ArgumentPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* A JDBC implementation of an {@link OAuth2AuthorizedClientService} that uses a
* {@link JdbcOperations} for {@link OAuth2AuthorizedClient} persistence.
*
* <p>
* <b>NOTE:</b> This {@code OAuth2AuthorizedClientService} depends on the table definition
* described in
* "classpath:org/springframework/security/oauth2/client/oauth2-client-schema.sql" and
* therefore MUST be defined in the database schema.
*
* @author Joe Grandja
* @author Stav Shamir
* @author Craig Andrews
* @since 5.3
* @see OAuth2AuthorizedClientService
* @see OAuth2AuthorizedClient
* @see JdbcOperations
* @see RowMapper
*/
public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService {
// @formatter:off
private static final String COLUMN_NAMES = "client_registration_id, "
+ "principal_name, "
+ "access_token_type, "
+ "access_token_value, "
+ "access_token_issued_at, "
+ "access_token_expires_at, "
+ "access_token_scopes, "
+ "refresh_token_value, "
+ "refresh_token_issued_at";
// @formatter:on
private static final String TABLE_NAME = "oauth2_authorized_client";
private static final String PK_FILTER = "client_registration_id = ? AND principal_name = ?";
// @formatter:off
private static final String LOAD_AUTHORIZED_CLIENT_SQL = "SELECT " + COLUMN_NAMES
+ " FROM " + TABLE_NAME
+ " WHERE " + PK_FILTER;
// @formatter:on
// @formatter:off
private static final String SAVE_AUTHORIZED_CLIENT_SQL = "INSERT INTO " + TABLE_NAME
+ " (" + COLUMN_NAMES + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
// @formatter:on
private static final String REMOVE_AUTHORIZED_CLIENT_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + PK_FILTER;
// @formatter:off
private static final String UPDATE_AUTHORIZED_CLIENT_SQL = "UPDATE " + TABLE_NAME
+ " SET access_token_type = ?, access_token_value = ?, access_token_issued_at = ?,"
+ " access_token_expires_at = ?, access_token_scopes = ?,"
+ " refresh_token_value = ?, refresh_token_issued_at = ?"
+ " WHERE " + PK_FILTER;
// @formatter:on
protected final JdbcOperations jdbcOperations;
protected RowMapper<OAuth2AuthorizedClient> authorizedClientRowMapper;
protected Function<OAuth2AuthorizedClientHolder, List<SqlParameterValue>> authorizedClientParametersMapper;
protected final LobHandler lobHandler;
/**
* Constructs a {@code JdbcOAuth2AuthorizedClientService} using the provided
* parameters.
* @param jdbcOperations the JDBC operations
* @param clientRegistrationRepository the repository of client registrations
*/
public JdbcOAuth2AuthorizedClientService(JdbcOperations jdbcOperations,
ClientRegistrationRepository clientRegistrationRepository) {
this(jdbcOperations, clientRegistrationRepository, new DefaultLobHandler());
}
/**
* Constructs a {@code JdbcOAuth2AuthorizedClientService} using the provided
* parameters.
* @param jdbcOperations the JDBC operations
* @param clientRegistrationRepository the repository of client registrations
* @param lobHandler the handler for large binary fields and large text fields
* @since 5.5
*/
public JdbcOAuth2AuthorizedClientService(JdbcOperations jdbcOperations,
ClientRegistrationRepository clientRegistrationRepository, LobHandler lobHandler) {
Assert.notNull(jdbcOperations, "jdbcOperations cannot be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(lobHandler, "lobHandler cannot be null");
this.jdbcOperations = jdbcOperations;
this.lobHandler = lobHandler;
OAuth2AuthorizedClientRowMapper authorizedClientRowMapper = new OAuth2AuthorizedClientRowMapper(
clientRegistrationRepository);
authorizedClientRowMapper.setLobHandler(lobHandler);
this.authorizedClientRowMapper = authorizedClientRowMapper;
this.authorizedClientParametersMapper = new OAuth2AuthorizedClientParametersMapper();
}
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, clientRegistrationId),
new SqlParameterValue(Types.VARCHAR, principalName) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
List<OAuth2AuthorizedClient> result = this.jdbcOperations.query(LOAD_AUTHORIZED_CLIENT_SQL, pss,
this.authorizedClientRowMapper);
return !result.isEmpty() ? (T) result.get(0) : null;
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
boolean existsAuthorizedClient = null != this.loadAuthorizedClient(
authorizedClient.getClientRegistration().getRegistrationId(), principal.getName());
if (existsAuthorizedClient) {
updateAuthorizedClient(authorizedClient, principal);
}
else {
try {
insertAuthorizedClient(authorizedClient, principal);
}
catch (DuplicateKeyException ex) {
updateAuthorizedClient(authorizedClient, principal);
}
}
}
private void updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
SqlParameterValue clientRegistrationIdParameter = parameters.remove(0);
SqlParameterValue principalNameParameter = parameters.remove(0);
parameters.add(clientRegistrationIdParameter);
parameters.add(principalNameParameter);
try (LobCreator lobCreator = this.lobHandler.getLobCreator()) {
PreparedStatementSetter pss = new LobCreatorArgumentPreparedStatementSetter(lobCreator,
parameters.toArray());
this.jdbcOperations.update(UPDATE_AUTHORIZED_CLIENT_SQL, pss);
}
}
private void insertAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
try (LobCreator lobCreator = this.lobHandler.getLobCreator()) {
PreparedStatementSetter pss = new LobCreatorArgumentPreparedStatementSetter(lobCreator,
parameters.toArray());
this.jdbcOperations.update(SAVE_AUTHORIZED_CLIENT_SQL, pss);
}
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, clientRegistrationId),
new SqlParameterValue(Types.VARCHAR, principalName) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(REMOVE_AUTHORIZED_CLIENT_SQL, pss);
}
/**
* Sets the {@link RowMapper} used for mapping the current row in
* {@code java.sql.ResultSet} to {@link OAuth2AuthorizedClient}. The default is
* {@link OAuth2AuthorizedClientRowMapper}.
* @param authorizedClientRowMapper the {@link RowMapper} used for mapping the current
* row in {@code java.sql.ResultSet} to {@link OAuth2AuthorizedClient}
*/
public final void setAuthorizedClientRowMapper(RowMapper<OAuth2AuthorizedClient> authorizedClientRowMapper) {
Assert.notNull(authorizedClientRowMapper, "authorizedClientRowMapper cannot be null");
this.authorizedClientRowMapper = authorizedClientRowMapper;
}
/**
* Sets the {@code Function} used for mapping {@link OAuth2AuthorizedClientHolder} to
* a {@code List} of {@link SqlParameterValue}. The default is
* {@link OAuth2AuthorizedClientParametersMapper}.
* @param authorizedClientParametersMapper the {@code Function} used for mapping
* {@link OAuth2AuthorizedClientHolder} to a {@code List} of {@link SqlParameterValue}
*/
public final void setAuthorizedClientParametersMapper(
Function<OAuth2AuthorizedClientHolder, List<SqlParameterValue>> authorizedClientParametersMapper) {
Assert.notNull(authorizedClientParametersMapper, "authorizedClientParametersMapper cannot be null");
this.authorizedClientParametersMapper = authorizedClientParametersMapper;
}
/**
* The default {@link RowMapper} that maps the current row in
* {@code java.sql.ResultSet} to {@link OAuth2AuthorizedClient}.
*/
public static class OAuth2AuthorizedClientRowMapper implements RowMapper<OAuth2AuthorizedClient> {
protected final ClientRegistrationRepository clientRegistrationRepository;
protected LobHandler lobHandler = new DefaultLobHandler();
public OAuth2AuthorizedClientRowMapper(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
public final void setLobHandler(LobHandler lobHandler) {
Assert.notNull(lobHandler, "lobHandler cannot be null");
this.lobHandler = lobHandler;
}
@Override
public OAuth2AuthorizedClient mapRow(ResultSet rs, int rowNum) throws SQLException {
String clientRegistrationId = rs.getString("client_registration_id");
ClientRegistration clientRegistration = this.clientRegistrationRepository
.findByRegistrationId(clientRegistrationId);
if (clientRegistration == null) {
throw new DataRetrievalFailureException(
"The ClientRegistration with id '" + clientRegistrationId + "' exists in the data source, "
+ "however, it was not found in the ClientRegistrationRepository.");
}
OAuth2AccessToken.TokenType tokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(rs.getString("access_token_type"))) {
tokenType = OAuth2AccessToken.TokenType.BEARER;
}
String tokenValue = new String(this.lobHandler.getBlobAsBytes(rs, "access_token_value"),
StandardCharsets.UTF_8);
Instant issuedAt = rs.getTimestamp("access_token_issued_at").toInstant();
Instant expiresAt = rs.getTimestamp("access_token_expires_at").toInstant();
Set<String> scopes = Collections.emptySet();
String accessTokenScopes = rs.getString("access_token_scopes");
if (accessTokenScopes != null) {
scopes = StringUtils.commaDelimitedListToSet(accessTokenScopes);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(tokenType, tokenValue, issuedAt, expiresAt, scopes);
OAuth2RefreshToken refreshToken = null;
byte[] refreshTokenValue = this.lobHandler.getBlobAsBytes(rs, "refresh_token_value");
if (refreshTokenValue != null) {
tokenValue = new String(refreshTokenValue, StandardCharsets.UTF_8);
issuedAt = null;
Timestamp refreshTokenIssuedAt = rs.getTimestamp("refresh_token_issued_at");
if (refreshTokenIssuedAt != null) {
issuedAt = refreshTokenIssuedAt.toInstant();
}
refreshToken = new OAuth2RefreshToken(tokenValue, issuedAt);
}
String principalName = rs.getString("principal_name");
return new OAuth2AuthorizedClient(clientRegistration, principalName, accessToken, refreshToken);
}
}
/**
* The default {@code Function} that maps {@link OAuth2AuthorizedClientHolder} to a
* {@code List} of {@link SqlParameterValue}.
*/
public static class OAuth2AuthorizedClientParametersMapper
implements Function<OAuth2AuthorizedClientHolder, List<SqlParameterValue>> {
@Override
public List<SqlParameterValue> apply(OAuth2AuthorizedClientHolder authorizedClientHolder) {
OAuth2AuthorizedClient authorizedClient = authorizedClientHolder.getAuthorizedClient();
Authentication principal = authorizedClientHolder.getPrincipal();
ClientRegistration clientRegistration = authorizedClient.getClientRegistration();
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
OAuth2RefreshToken refreshToken = authorizedClient.getRefreshToken();
List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, clientRegistration.getRegistrationId()));
parameters.add(new SqlParameterValue(Types.VARCHAR, principal.getName()));
parameters.add(new SqlParameterValue(Types.VARCHAR, accessToken.getTokenType().getValue()));
parameters.add(
new SqlParameterValue(Types.BLOB, accessToken.getTokenValue().getBytes(StandardCharsets.UTF_8)));
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(accessToken.getIssuedAt())));
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(accessToken.getExpiresAt())));
String accessTokenScopes = null;
if (!CollectionUtils.isEmpty(accessToken.getScopes())) {
accessTokenScopes = StringUtils.collectionToDelimitedString(accessToken.getScopes(), ",");
}
parameters.add(new SqlParameterValue(Types.VARCHAR, accessTokenScopes));
byte[] refreshTokenValue = null;
Timestamp refreshTokenIssuedAt = null;
if (refreshToken != null) {
refreshTokenValue = refreshToken.getTokenValue().getBytes(StandardCharsets.UTF_8);
if (refreshToken.getIssuedAt() != null) {
refreshTokenIssuedAt = Timestamp.from(refreshToken.getIssuedAt());
}
}
parameters.add(new SqlParameterValue(Types.BLOB, refreshTokenValue));
parameters.add(new SqlParameterValue(Types.TIMESTAMP, refreshTokenIssuedAt));
return parameters;
}
}
/**
* A holder for an {@link OAuth2AuthorizedClient} and End-User {@link Authentication}
* (Resource Owner).
*/
public static final class OAuth2AuthorizedClientHolder {
private final OAuth2AuthorizedClient authorizedClient;
private final Authentication principal;
/**
* Constructs an {@code OAuth2AuthorizedClientHolder} using the provided
* parameters.
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
*/
public OAuth2AuthorizedClientHolder(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
this.authorizedClient = authorizedClient;
this.principal = principal;
}
/**
* Returns the {@link OAuth2AuthorizedClient}.
* @return the {@link OAuth2AuthorizedClient}
*/
public OAuth2AuthorizedClient getAuthorizedClient() {
return this.authorizedClient;
}
/**
* Returns the End-User {@link Authentication} (Resource Owner).
* @return the End-User {@link Authentication} (Resource Owner)
*/
public Authentication getPrincipal() {
return this.principal;
}
}
private static final class LobCreatorArgumentPreparedStatementSetter extends ArgumentPreparedStatementSetter {
protected final LobCreator lobCreator;
private LobCreatorArgumentPreparedStatementSetter(LobCreator lobCreator, Object[] args) {
super(args);
this.lobCreator = lobCreator;
}
@Override
protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException {
if (argValue instanceof SqlParameterValue paramValue) {
if (paramValue.getSqlType() == Types.BLOB) {
if (paramValue.getValue() != null) {
Assert.isInstanceOf(byte[].class, paramValue.getValue(),
"Value of blob parameter must be byte[]");
}
byte[] valueBytes = (byte[]) paramValue.getValue();
this.lobCreator.setBlobAsBytes(ps, parameterPosition, valueBytes);
return;
}
}
super.doSetValue(ps, parameterPosition, argValue);
}
}
}
| 17,911 | 42.057692 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/JwtBearerReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2022 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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.WebClientReactiveJwtBearerTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.Assert;
/**
* An implementation of an {@link ReactiveOAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#JWT_BEARER jwt-bearer} grant.
*
* @author Steve Riesenberg
* @since 5.6
* @see ReactiveOAuth2AuthorizedClientProvider
* @see WebClientReactiveJwtBearerTokenResponseClient
*/
public final class JwtBearerReactiveOAuth2AuthorizedClientProvider implements ReactiveOAuth2AuthorizedClientProvider {
private ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient = new WebClientReactiveJwtBearerTokenResponseClient();
private Function<OAuth2AuthorizationContext, Mono<Jwt>> jwtAssertionResolver = this::resolveJwtAssertion;
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns an empty {@code Mono} if authorization (or
* re-authorization) is not supported, e.g. the client's
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is
* not {@link AuthorizationGrantType#JWT_BEARER jwt-bearer} OR the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* authorization is not supported
*/
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
return Mono.empty();
}
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized but access token is NOT expired than no
// need for re-authorization
return Mono.empty();
}
// As per spec, in section 4.1 Using Assertions as Authorization Grants
// https://tools.ietf.org/html/rfc7521#section-4.1
//
// An assertion used in this context is generally a short-lived
// representation of the authorization grant, and authorization servers
// SHOULD NOT issue access tokens with a lifetime that exceeds the
// validity period of the assertion by a significant period. In
// practice, that will usually mean that refresh tokens are not issued
// in response to assertion grant requests, and access tokens will be
// issued with a reasonably short lifetime. Clients can refresh an
// expired access token by requesting a new one using the same
// assertion, if it is still valid, or with a new assertion.
// @formatter:off
return this.jwtAssertionResolver.apply(context)
.map((jwt) -> new JwtBearerGrantRequest(clientRegistration, jwt))
.flatMap(this.accessTokenResponseClient::getTokenResponse)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(),
ex))
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken()));
// @formatter:on
}
private Mono<Jwt> resolveJwtAssertion(OAuth2AuthorizationContext context) {
// @formatter:off
return Mono.just(context)
.map((ctx) -> ctx.getPrincipal().getPrincipal())
.filter((principal) -> principal instanceof Jwt)
.cast(Jwt.class);
// @formatter:on
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code jwt-bearer} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code jwt-bearer} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the resolver used for resolving the {@link Jwt} assertion.
* @param jwtAssertionResolver the resolver used for resolving the {@link Jwt}
* assertion
* @since 5.7
*/
public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Mono<Jwt>> jwtAssertionResolver) {
Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null");
this.jwtAssertionResolver = jwtAssertionResolver;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 7,248 | 41.641176 | 152 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizationFailureHandler.java | /*
* Copyright 2002-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.client;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
/**
* Handles when an OAuth 2.0 Client fails to authorize (or re-authorize) via the
* authorization server or resource server.
*
* @author Phil Clay
* @since 5.3
*/
@FunctionalInterface
public interface ReactiveOAuth2AuthorizationFailureHandler {
/**
* Called when an OAuth 2.0 Client fails to authorize (or re-authorize) via the
* authorization server or resource server.
* @param authorizationException the exception that contains details about what failed
* @param principal the {@code Principal} that was attempted to be authorized
* @param attributes an immutable {@code Map} of extra optional attributes present
* under certain conditions. For example, this might contain a
* {@link org.springframework.web.server.ServerWebExchange ServerWebExchange} if the
* authorization was performed within the context of a {@code ServerWebExchange}.
* @return an empty {@link Mono} that completes after this handler has finished
* handling the event.
*/
Mono<Void> onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal,
Map<String, Object> attributes);
}
| 2,004 | 37.557692 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/package-info.java | /*
* Copyright 2002-2017 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.
*/
/**
* Core classes and interfaces providing support for OAuth 2.0 Client.
*/
package org.springframework.security.oauth2.client;
| 754 | 34.952381 | 75 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ClientAuthorizationRequiredException.java | /*
* Copyright 2002-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.client;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* This exception is thrown when an OAuth 2.0 Client is required to obtain authorization
* from the Resource Owner.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizedClient
*/
public class ClientAuthorizationRequiredException extends ClientAuthorizationException {
private static final String CLIENT_AUTHORIZATION_REQUIRED_ERROR_CODE = "client_authorization_required";
/**
* Constructs a {@code ClientAuthorizationRequiredException} using the provided
* parameters.
* @param clientRegistrationId the identifier for the client's registration
*/
public ClientAuthorizationRequiredException(String clientRegistrationId) {
super(new OAuth2Error(CLIENT_AUTHORIZATION_REQUIRED_ERROR_CODE,
"Authorization required for Client Registration Id: " + clientRegistrationId, null),
clientRegistrationId);
}
}
| 1,578 | 34.088889 | 104 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2019 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.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.util.Assert;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientProvider} that simply
* delegates to it's internal {@code List} of
* {@link ReactiveOAuth2AuthorizedClientProvider}(s).
* <p>
* Each provider is given a chance to
* {@link ReactiveOAuth2AuthorizedClientProvider#authorize(OAuth2AuthorizationContext)
* authorize} the {@link OAuth2AuthorizationContext#getClientRegistration() client} in the
* provided context with the first available {@link OAuth2AuthorizedClient} being
* returned.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
*/
public final class DelegatingReactiveOAuth2AuthorizedClientProvider implements ReactiveOAuth2AuthorizedClientProvider {
private final List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders;
/**
* Constructs a {@code DelegatingReactiveOAuth2AuthorizedClientProvider} using the
* provided parameters.
* @param authorizedClientProviders a list of
* {@link ReactiveOAuth2AuthorizedClientProvider}(s)
*/
public DelegatingReactiveOAuth2AuthorizedClientProvider(
ReactiveOAuth2AuthorizedClientProvider... authorizedClientProviders) {
Assert.notEmpty(authorizedClientProviders, "authorizedClientProviders cannot be empty");
this.authorizedClientProviders = Collections.unmodifiableList(Arrays.asList(authorizedClientProviders));
}
/**
* Constructs a {@code DelegatingReactiveOAuth2AuthorizedClientProvider} using the
* provided parameters.
* @param authorizedClientProviders a {@code List} of
* {@link OAuth2AuthorizedClientProvider}(s)
*/
public DelegatingReactiveOAuth2AuthorizedClientProvider(
List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders) {
Assert.notEmpty(authorizedClientProviders, "authorizedClientProviders cannot be empty");
this.authorizedClientProviders = Collections.unmodifiableList(new ArrayList<>(authorizedClientProviders));
}
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
return Flux.fromIterable(this.authorizedClientProviders)
.concatMap((authorizedClientProvider) -> authorizedClientProvider.authorize(context)).next();
}
}
| 3,129 | 38.125 | 119 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientService.java | /*
* Copyright 2002-2019 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.client;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.util.Assert;
/**
* An {@link OAuth2AuthorizedClientService} that stores {@link OAuth2AuthorizedClient
* Authorized Client(s)} in-memory.
*
* @author Rob Winch
* @author Vedran Pavic
* @since 5.1
* @see OAuth2AuthorizedClientService
* @see OAuth2AuthorizedClient
* @see ClientRegistration
* @see Authentication
*/
public final class InMemoryReactiveOAuth2AuthorizedClientService implements ReactiveOAuth2AuthorizedClientService {
private final Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients = new ConcurrentHashMap<>();
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
/**
* Constructs an {@code InMemoryReactiveOAuth2AuthorizedClientService} using the
* provided parameters.
* @param clientRegistrationRepository the repository of client registrations
*/
public InMemoryReactiveOAuth2AuthorizedClientService(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (Mono<T>) this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
.map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
.flatMap((identifier) -> Mono.justOrEmpty(this.authorizedClients.get(identifier)));
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
return Mono.fromRunnable(() -> {
OAuth2AuthorizedClientId identifier = new OAuth2AuthorizedClientId(
authorizedClient.getClientRegistration().getRegistrationId(), principal.getName());
this.authorizedClients.put(identifier, authorizedClient);
});
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
// @formatter:off
return this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
.map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
.doOnNext(this.authorizedClients::remove)
.then(Mono.empty());
// @formatter:on
}
}
| 3,856 | 40.473118 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientManager.java | /*
* Copyright 2002-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.client;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
/**
* Implementations of this interface are responsible for the overall management of
* {@link OAuth2AuthorizedClient Authorized Client(s)}.
*
* <p>
* The primary responsibilities include:
* <ol>
* <li>Authorizing (or re-authorizing) an OAuth 2.0 Client by leveraging a
* {@link ReactiveOAuth2AuthorizedClientProvider}(s).</li>
* <li>Delegating the persistence of an {@link OAuth2AuthorizedClient}, typically using a
* {@link ReactiveOAuth2AuthorizedClientService} OR
* {@link ServerOAuth2AuthorizedClientRepository}.</li>
* </ol>
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClient
* @see ReactiveOAuth2AuthorizedClientProvider
* @see ReactiveOAuth2AuthorizedClientService
* @see ServerOAuth2AuthorizedClientRepository
*/
@FunctionalInterface
public interface ReactiveOAuth2AuthorizedClientManager {
/**
* Attempt to authorize or re-authorize (if required) the {@link ClientRegistration
* client} identified by the provided
* {@link OAuth2AuthorizeRequest#getClientRegistrationId() clientRegistrationId}.
* Implementations must return an empty {@code Mono} if authorization is not supported
* for the specified client, e.g. the associated
* {@link ReactiveOAuth2AuthorizedClientProvider}(s) does not support the
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant} type
* configured for the client.
*
* <p>
* In the case of re-authorization, implementations must return the provided
* {@link OAuth2AuthorizeRequest#getAuthorizedClient() authorized client} if
* re-authorization is not supported for the client OR is not required, e.g. a
* {@link OAuth2AuthorizedClient#getRefreshToken() refresh token} is not available OR
* the {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
* @param authorizeRequest the authorize request
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* authorization is not supported for the specified client
*/
Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest);
}
| 2,970 | 40.84507 | 100 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.oauth2.client;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} grant.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
*/
public final class AuthorizationCodeOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
/**
* Attempt to authorize the {@link OAuth2AuthorizationContext#getClientRegistration()
* client} in the provided {@code context}. Returns {@code null} if authorization is
* not supported, e.g. the client's
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is
* not {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} OR the
* client is already authorized.
* @param context the context that holds authorization-specific state for the client
* @return {@code null} if authorization is not supported or the client is already
* authorized
* @throws ClientAuthorizationRequiredException in order to trigger authorization in
* which the {@link OAuth2AuthorizationRequestRedirectFilter} will catch and initiate
* the authorization request
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(
context.getClientRegistration().getAuthorizationGrantType()) && context.getAuthorizedClient() == null) {
// ClientAuthorizationRequiredException is caught by
// OAuth2AuthorizationRequestRedirectFilter which initiates authorization
throw new ClientAuthorizationRequiredException(context.getClientRegistration().getRegistrationId());
}
return null;
}
}
| 2,756 | 42.761905 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationSuccessHandler.java | /*
* Copyright 2002-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.client;
import java.util.Map;
import org.springframework.security.core.Authentication;
/**
* Handles when an OAuth 2.0 Client has been successfully authorized (or re-authorized)
* via the Authorization Server.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientManager
*/
@FunctionalInterface
public interface OAuth2AuthorizationSuccessHandler {
/**
* Called when an OAuth 2.0 Client has been successfully authorized (or re-authorized)
* via the Authorization Server.
* @param authorizedClient the client that was successfully authorized (or
* re-authorized)
* @param principal the {@code Principal} associated with the authorized client
* @param attributes an immutable {@code Map} of (optional) attributes present under
* certain conditions. For example, this might contain a
* {@code jakarta.servlet.http.HttpServletRequest} and
* {@code jakarta.servlet.http.HttpServletResponse} if the authorization was performed
* within the context of a {@code jakarta.servlet.ServletContext}.
*/
void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
Map<String, Object> attributes);
}
| 1,869 | 35.666667 | 95 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
/**
* A strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. Implementations
* will typically implement a specific {@link AuthorizationGrantType authorization grant}
* type.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizationContext
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section
* 1.3 Authorization Grant</a>
*/
@FunctionalInterface
public interface ReactiveOAuth2AuthorizedClientProvider {
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* context. Implementations must return an empty {@code Mono} if authorization is not
* supported for the specified client, e.g. the provider doesn't support the
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant} type
* configured for the client.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* authorization is not supported for the specified client
*/
Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context);
}
| 2,094 | 38.528302 | 89 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.WebClientReactiveRefreshTokenTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.util.Assert;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#REFRESH_TOKEN refresh_token} grant.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
* @see WebClientReactiveRefreshTokenTokenResponseClient
*/
public final class RefreshTokenReactiveOAuth2AuthorizedClientProvider
implements ReactiveOAuth2AuthorizedClientProvider {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient = new WebClientReactiveRefreshTokenTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to re-authorize the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns an empty {@code Mono} if re-authorization is not
* supported, e.g. the client is not authorized OR the
* {@link OAuth2AuthorizedClient#getRefreshToken() refresh token} is not available for
* the authorized client OR the {@link OAuth2AuthorizedClient#getAccessToken() access
* token} is not expired.
*
* <p>
* The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
* are supported:
* <ol>
* <li>{@code "org.springframework.security.oauth2.client.REQUEST_SCOPE"} (optional) -
* a {@code String[]} of scope(s) to be requested by the
* {@link OAuth2AuthorizationContext#getClientRegistration() client}</li>
* </ol>
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* re-authorization is not supported
*/
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient == null || authorizedClient.getRefreshToken() == null
|| !hasTokenExpired(authorizedClient.getAccessToken())) {
return Mono.empty();
}
Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
Set<String> scopes = Collections.emptySet();
if (requestScope != null) {
Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
scopes = new HashSet<>(Arrays.asList((String[]) requestScope));
}
ClientRegistration clientRegistration = context.getClientRegistration();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes);
return Mono.just(refreshTokenGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse)
.onErrorMap(OAuth2AuthorizationException.class,
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
e))
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code refresh_token} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code refresh_token} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 6,410 | 42.612245 | 164 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#REFRESH_TOKEN refresh_token} grant.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
* @see DefaultRefreshTokenTokenResponseClient
*/
public final class RefreshTokenOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
private OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to re-authorize the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns {@code null} if re-authorization is not supported, e.g.
* the client is not authorized OR the {@link OAuth2AuthorizedClient#getRefreshToken()
* refresh token} is not available for the authorized client OR the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
*
* <p>
* The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
* are supported:
* <ol>
* <li>{@link OAuth2AuthorizationContext#REQUEST_SCOPE_ATTRIBUTE_NAME} (optional) - a
* {@code String[]} of scope(s) to be requested by the
* {@link OAuth2AuthorizationContext#getClientRegistration() client}</li>
* </ol>
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if re-authorization is
* not supported
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient == null || authorizedClient.getRefreshToken() == null
|| !hasTokenExpired(authorizedClient.getAccessToken())) {
return null;
}
Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
Set<String> scopes = Collections.emptySet();
if (requestScope != null) {
Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
scopes = new HashSet<>(Arrays.asList((String[]) requestScope));
}
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
authorizedClient.getClientRegistration(), authorizedClient.getAccessToken(),
authorizedClient.getRefreshToken(), scopes);
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(authorizedClient, refreshTokenGrantRequest);
return new OAuth2AuthorizedClient(context.getAuthorizedClient().getClientRegistration(),
context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
}
private OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizedClient authorizedClient,
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(refreshTokenGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(),
authorizedClient.getClientRegistration().getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code refresh_token} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code refresh_token} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 6,538 | 41.738562 | 146 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2022 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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.WebClientReactivePasswordTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#PASSWORD password} grant.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
* @see WebClientReactivePasswordTokenResponseClient
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use of
* the Resource Owner Password Credentials grant. See reference <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public final class PasswordReactiveOAuth2AuthorizedClientProvider implements ReactiveOAuth2AuthorizedClientProvider {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient = new WebClientReactivePasswordTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns an empty {@code Mono} if authorization (or
* re-authorization) is not supported, e.g. the client's
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is
* not {@link AuthorizationGrantType#PASSWORD password} OR the
* {@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME username} and/or
* {@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME password} attributes are
* not available in the provided {@code context} OR the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
*
* <p>
* The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
* are supported:
* <ol>
* <li>{@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME} (required) - a
* {@code String} value for the resource owner's username</li>
* <li>{@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME} (required) - a
* {@code String} value for the resource owner's password</li>
* </ol>
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* authorization (or re-authorization) is not supported
*/
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (!AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType())) {
return Mono.empty();
}
String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
return Mono.empty();
}
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized and access token is NOT expired than no
// need for re-authorization
return Mono.empty();
}
if (authorizedClient != null && hasTokenExpired(authorizedClient.getAccessToken())
&& authorizedClient.getRefreshToken() != null) {
// If client is already authorized and access token is expired and a refresh
// token is available,
// than return and allow RefreshTokenReactiveOAuth2AuthorizedClientProvider to
// handle the refresh
return Mono.empty();
}
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username,
password);
return Mono.just(passwordGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse)
.onErrorMap(OAuth2AuthorizationException.class,
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
e))
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code password} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code password} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 7,338 | 44.302469 | 156 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.java | /*
* Copyright 2002-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.client;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientManager} that is capable of
* operating outside of the context of a {@link ServerWebExchange}, e.g. in a
* scheduled/background thread and/or in the service-tier.
*
* <p>
* (When operating <em>within</em> the context of a {@link ServerWebExchange}, use
* {@link DefaultReactiveOAuth2AuthorizedClientManager} instead.)
* </p>
*
* <p>
* This is a reactive equivalent of
* {@link org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager}.
* </p>
*
* <h2>Authorized Client Persistence</h2>
*
* <p>
* This client manager utilizes a {@link ReactiveOAuth2AuthorizedClientService} to persist
* {@link OAuth2AuthorizedClient}s.
* </p>
*
* <p>
* By default, when an authorization attempt succeeds, the {@link OAuth2AuthorizedClient}
* will be saved in the authorized client service. This functionality can be changed by
* configuring a custom {@link ReactiveOAuth2AuthorizationSuccessHandler} via
* {@link #setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)}.
* </p>
*
* <p>
* By default, when an authorization attempt fails due to an
* {@value org.springframework.security.oauth2.core.OAuth2ErrorCodes#INVALID_GRANT} error,
* the previously saved {@link OAuth2AuthorizedClient} will be removed from the authorized
* client service. (The
* {@value org.springframework.security.oauth2.core.OAuth2ErrorCodes#INVALID_GRANT} error
* generally occurs when a refresh token that is no longer valid is used to retrieve a new
* access token.) This functionality can be changed by configuring a custom
* {@link ReactiveOAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)}.
* </p>
*
* @author Ankur Pathak
* @author Phil Clay
* @since 5.2.2
* @see ReactiveOAuth2AuthorizedClientManager
* @see ReactiveOAuth2AuthorizedClientProvider
* @see ReactiveOAuth2AuthorizedClientService
* @see ReactiveOAuth2AuthorizationSuccessHandler
* @see ReactiveOAuth2AuthorizationFailureHandler
*/
public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
implements ReactiveOAuth2AuthorizedClientManager {
private static final ReactiveOAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder().clientCredentials().build();
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
private final ReactiveOAuth2AuthorizedClientService authorizedClientService;
private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper = new DefaultContextAttributesMapper();
private ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
/**
* Constructs an {@code AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager}
* using the provided parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientService the authorized client service
*/
public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ReactiveOAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientService = authorizedClientService;
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientService
.saveAuthorizedClient(authorizedClient, principal);
this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> this.authorizedClientService
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
}
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
return createAuthorizationContext(authorizeRequest)
.flatMap((authorizationContext) -> authorize(authorizationContext, authorizeRequest.getPrincipal()));
}
private Mono<OAuth2AuthorizationContext> createAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest) {
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
Authentication principal = authorizeRequest.getPrincipal();
return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient())
.map(OAuth2AuthorizationContext::withAuthorizedClient)
.switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository
.findByRegistrationId(clientRegistrationId)
.flatMap((clientRegistration) -> this.authorizedClientService
.loadAuthorizedClient(clientRegistrationId, principal.getName())
.map(OAuth2AuthorizationContext::withAuthorizedClient)
.switchIfEmpty(Mono.fromSupplier(
() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration))))
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))))
.flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest)
.defaultIfEmpty(Collections.emptyMap()).map((contextAttributes) -> {
OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal);
if (!contextAttributes.isEmpty()) {
builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
}
return builder.build();
}));
}
/**
* Performs authorization and then delegates to either the
* {@link #authorizationSuccessHandler} or {@link #authorizationFailureHandler},
* depending on the authorization result.
* @param authorizationContext the context to authorize
* @param principal the principle to authorize
* @return a {@link Mono} that emits the authorized client after the authorization
* attempt succeeds and the {@link #authorizationSuccessHandler} has completed, or
* completes with an exception after the authorization attempt fails and the
* {@link #authorizationFailureHandler} has completed
*/
private Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext authorizationContext,
Authentication principal) {
return this.authorizedClientProvider.authorize(authorizationContext)
// Delegate to the authorizationSuccessHandler of the successful
// authorization
.flatMap((authorizedClient) -> this.authorizationSuccessHandler
.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap())
.thenReturn(authorizedClient))
// Delegate to the authorizationFailureHandler of the failed authorization
.onErrorResume(OAuth2AuthorizationException.class,
(authorizationException) -> this.authorizationFailureHandler
.onAuthorizationFailure(authorizationException, principal, Collections.emptyMap())
.then(Mono.error(authorizationException)))
.switchIfEmpty(Mono.defer(() -> Mono.justOrEmpty(authorizationContext.getAuthorizedClient())));
}
/**
* Sets the {@link ReactiveOAuth2AuthorizedClientProvider} used for authorizing (or
* re-authorizing) an OAuth 2.0 Client.
* @param authorizedClientProvider the {@link ReactiveOAuth2AuthorizedClientProvider}
* used for authorizing (or re-authorizing) an OAuth 2.0 Client
*/
public void setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) {
Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null");
this.authorizedClientProvider = authorizedClientProvider;
}
/**
* Sets the {@code Function} used for mapping attribute(s) from the
* {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to
* the {@link OAuth2AuthorizationContext#getAttributes() authorization context}.
* @param contextAttributesMapper the {@code Function} used for supplying the
* {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes()
* authorization context}
*/
public void setContextAttributesMapper(
Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper) {
Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null");
this.contextAttributesMapper = contextAttributesMapper;
}
/**
* Sets the handler that handles successful authorizations.
*
* The default saves {@link OAuth2AuthorizedClient}s in the
* {@link ReactiveOAuth2AuthorizedClientService}.
* @param authorizationSuccessHandler the handler that handles successful
* authorizations.
* @since 5.3
*/
public void setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler) {
Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null");
this.authorizationSuccessHandler = authorizationSuccessHandler;
}
/**
* Sets the handler that handles authorization failures.
*
* <p>
* A {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is used
* by default.
* </p>
* @param authorizationFailureHandler the handler that handles authorization failures.
* @since 5.3
* @see RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
*/
public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
}
/**
* The default implementation of the {@link #setContextAttributesMapper(Function)
* contextAttributesMapper}.
*/
public static class DefaultContextAttributesMapper
implements Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> {
private final AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper mapper = new AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper();
@Override
public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) {
return Mono.fromCallable(() -> this.mapper.apply(authorizeRequest));
}
}
}
| 11,860 | 46.444 | 199 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.oauth2.client;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationRequestRedirectWebFilter;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} grant.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
*/
public final class AuthorizationCodeReactiveOAuth2AuthorizedClientProvider
implements ReactiveOAuth2AuthorizedClientProvider {
/**
* Attempt to authorize the {@link OAuth2AuthorizationContext#getClientRegistration()
* client} in the provided {@code context}. Returns an empty {@code Mono} if
* authorization is not supported, e.g. the client's
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is
* not {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} OR the
* client is already authorized.
* @param context the context that holds authorization-specific state for the client
* @return an empty {@code Mono} if authorization is not supported or the client is
* already authorized
* @throws ClientAuthorizationRequiredException in order to trigger authorization in
* which the {@link OAuth2AuthorizationRequestRedirectWebFilter} will catch and
* initiate the authorization request
*/
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(
context.getClientRegistration().getAuthorizationGrantType()) && context.getAuthorizedClient() == null) {
// ClientAuthorizationRequiredException is caught by
// OAuth2AuthorizationRequestRedirectWebFilter which initiates authorization
return Mono.error(() -> new ClientAuthorizationRequiredException(
context.getClientRegistration().getRegistrationId()));
}
return Mono.empty();
}
}
| 2,846 | 42.8 | 108 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManager.java | /*
* Copyright 2002-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.client;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link OAuth2AuthorizedClientManager} that is capable of
* operating outside of the context of a {@code HttpServletRequest}, e.g. in a
* scheduled/background thread and/or in the service-tier.
*
* <p>
* (When operating <em>within</em> the context of a {@code HttpServletRequest}, use
* {@link DefaultOAuth2AuthorizedClientManager} instead.)
*
* <h2>Authorized Client Persistence</h2>
*
* <p>
* This manager utilizes an {@link OAuth2AuthorizedClientService} to persist
* {@link OAuth2AuthorizedClient}s.
*
* <p>
* By default, when an authorization attempt succeeds, the {@link OAuth2AuthorizedClient}
* will be saved in the {@link OAuth2AuthorizedClientService}. This functionality can be
* changed by configuring a custom {@link OAuth2AuthorizationSuccessHandler} via
* {@link #setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)}.
*
* <p>
* By default, when an authorization attempt fails due to an
* {@value OAuth2ErrorCodes#INVALID_GRANT} error, the previously saved
* {@link OAuth2AuthorizedClient} will be removed from the
* {@link OAuth2AuthorizedClientService}. (The {@value OAuth2ErrorCodes#INVALID_GRANT}
* error can occur when a refresh token that is no longer valid is used to retrieve a new
* access token.) This functionality can be changed by configuring a custom
* {@link OAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)}.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientManager
* @see OAuth2AuthorizedClientProvider
* @see OAuth2AuthorizedClientService
* @see OAuth2AuthorizationSuccessHandler
* @see OAuth2AuthorizationFailureHandler
*/
public final class AuthorizedClientServiceOAuth2AuthorizedClientManager implements OAuth2AuthorizedClientManager {
private static final OAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = OAuth2AuthorizedClientProviderBuilder
.builder().clientCredentials().build();
private final ClientRegistrationRepository clientRegistrationRepository;
private final OAuth2AuthorizedClientService authorizedClientService;
private OAuth2AuthorizedClientProvider authorizedClientProvider;
private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper;
private OAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private OAuth2AuthorizationFailureHandler authorizationFailureHandler;
/**
* Constructs an {@code AuthorizedClientServiceOAuth2AuthorizedClientManager} using
* the provided parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientService the authorized client service
*/
public AuthorizedClientServiceOAuth2AuthorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientService = authorizedClientService;
this.authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
this.contextAttributesMapper = new DefaultContextAttributesMapper();
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientService
.saveAuthorizedClient(authorizedClient, principal);
this.authorizationFailureHandler = new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> authorizedClientService
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
}
@Nullable
@Override
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
OAuth2AuthorizedClient authorizedClient = authorizeRequest.getAuthorizedClient();
Authentication principal = authorizeRequest.getPrincipal();
OAuth2AuthorizationContext.Builder contextBuilder;
if (authorizedClient != null) {
contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
}
else {
ClientRegistration clientRegistration = this.clientRegistrationRepository
.findByRegistrationId(clientRegistrationId);
Assert.notNull(clientRegistration,
"Could not find ClientRegistration with id '" + clientRegistrationId + "'");
authorizedClient = this.authorizedClientService.loadAuthorizedClient(clientRegistrationId,
principal.getName());
if (authorizedClient != null) {
contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
}
else {
contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
}
}
OAuth2AuthorizationContext authorizationContext = buildAuthorizationContext(authorizeRequest, principal,
contextBuilder);
try {
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
}
catch (OAuth2AuthorizationException ex) {
this.authorizationFailureHandler.onAuthorizationFailure(ex, principal, Collections.emptyMap());
throw ex;
}
if (authorizedClient != null) {
this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal,
Collections.emptyMap());
}
else {
// In the case of re-authorization, the returned `authorizedClient` may be
// null if re-authorization is not supported.
// For these cases, return the provided
// `authorizationContext.authorizedClient`.
if (authorizationContext.getAuthorizedClient() != null) {
return authorizationContext.getAuthorizedClient();
}
}
return authorizedClient;
}
private OAuth2AuthorizationContext buildAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest,
Authentication principal, OAuth2AuthorizationContext.Builder contextBuilder) {
// @formatter:off
return contextBuilder.principal(principal)
.attributes((attributes) -> {
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
if (!CollectionUtils.isEmpty(contextAttributes)) {
attributes.putAll(contextAttributes);
}
})
.build();
// @formatter:on
}
/**
* Sets the {@link OAuth2AuthorizedClientProvider} used for authorizing (or
* re-authorizing) an OAuth 2.0 Client.
* @param authorizedClientProvider the {@link OAuth2AuthorizedClientProvider} used for
* authorizing (or re-authorizing) an OAuth 2.0 Client
*/
public void setAuthorizedClientProvider(OAuth2AuthorizedClientProvider authorizedClientProvider) {
Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null");
this.authorizedClientProvider = authorizedClientProvider;
}
/**
* Sets the {@code Function} used for mapping attribute(s) from the
* {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to
* the {@link OAuth2AuthorizationContext#getAttributes() authorization context}.
* @param contextAttributesMapper the {@code Function} used for supplying the
* {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes()
* authorization context}
*/
public void setContextAttributesMapper(
Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper) {
Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null");
this.contextAttributesMapper = contextAttributesMapper;
}
/**
* Sets the {@link OAuth2AuthorizationSuccessHandler} that handles successful
* authorizations.
*
* <p>
* The default saves {@link OAuth2AuthorizedClient}s in the
* {@link OAuth2AuthorizedClientService}.
* @param authorizationSuccessHandler the {@link OAuth2AuthorizationSuccessHandler}
* that handles successful authorizations
* @since 5.3
*/
public void setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler authorizationSuccessHandler) {
Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null");
this.authorizationSuccessHandler = authorizationSuccessHandler;
}
/**
* Sets the {@link OAuth2AuthorizationFailureHandler} that handles authorization
* failures.
*
* <p>
* A {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} is used by
* default.
* @param authorizationFailureHandler the {@link OAuth2AuthorizationFailureHandler}
* that handles authorization failures
* @since 5.3
* @see RemoveAuthorizedClientOAuth2AuthorizationFailureHandler
*/
public void setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
}
/**
* The default implementation of the {@link #setContextAttributesMapper(Function)
* contextAttributesMapper}.
*/
public static class DefaultContextAttributesMapper
implements Function<OAuth2AuthorizeRequest, Map<String, Object>> {
@Override
public Map<String, Object> apply(OAuth2AuthorizeRequest authorizeRequest) {
Map<String, Object> contextAttributes = Collections.emptyMap();
String scope = authorizeRequest.getAttribute(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope)) {
contextAttributes = new HashMap<>();
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
StringUtils.delimitedListToStringArray(scope, " "));
}
return contextAttributes;
}
}
}
| 11,246 | 42.593023 | 127 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationFailureHandler.java | /*
* Copyright 2002-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.client;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
/**
* Handles when an OAuth 2.0 Client fails to authorize (or re-authorize) via the
* Authorization Server or Resource Server.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientManager
*/
@FunctionalInterface
public interface OAuth2AuthorizationFailureHandler {
/**
* Called when an OAuth 2.0 Client fails to authorize (or re-authorize) via the
* Authorization Server or Resource Server.
* @param authorizationException the exception that contains details about what failed
* @param principal the {@code Principal} associated with the attempted authorization
* @param attributes an immutable {@code Map} of (optional) attributes present under
* certain conditions. For example, this might contain a
* {@code jakarta.servlet.http.HttpServletRequest} and
* {@code jakarta.servlet.http.HttpServletResponse} if the authorization was performed
* within the context of a {@code jakarta.servlet.ServletContext}.
*/
void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal,
Map<String, Object> attributes);
}
| 1,966 | 37.568627 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler.java | /*
* Copyright 2002-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.client;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.Assert;
/**
* A {@link ReactiveOAuth2AuthorizationFailureHandler} that removes an
* {@link OAuth2AuthorizedClient} when the {@link OAuth2Error#getErrorCode()} matches one
* of the configured {@link OAuth2ErrorCodes OAuth 2.0 error codes}.
*
* @author Phil Clay
* @since 5.3
*/
public class RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
implements ReactiveOAuth2AuthorizationFailureHandler {
/**
* The default OAuth 2.0 error codes that will trigger removal of the authorized
* client.
* @see OAuth2ErrorCodes
*/
public static final Set<String> DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES;
static {
Set<String> codes = new LinkedHashSet<>();
// Returned from resource servers when an access token provided is expired,
// revoked, malformed, or invalid for other reasons. Note that this is needed
// because the ServerOAuth2AuthorizedClientExchangeFilterFunction delegates this
// type of failure received from a resource server to this failure handler.
codes.add(OAuth2ErrorCodes.INVALID_TOKEN);
// Returned from authorization servers when a refresh token is invalid, expired,
// revoked, does not match the redirection URI used in the authorization request,
// or was issued to another client.
codes.add(OAuth2ErrorCodes.INVALID_GRANT);
DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES = Collections.unmodifiableSet(codes);
}
/**
* A delegate that removes an {@link OAuth2AuthorizedClient} from a
* {@link ServerOAuth2AuthorizedClientRepository} or
* {@link ReactiveOAuth2AuthorizedClientService} if the error code is one of the
* {@link #removeAuthorizedClientErrorCodes}.
*/
private final OAuth2AuthorizedClientRemover delegate;
/**
* The OAuth 2.0 Error Codes which will trigger removal of an authorized client.
* @see OAuth2ErrorCodes
*/
private final Set<String> removeAuthorizedClientErrorCodes;
/**
* Constructs a
* {@code RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} using the
* provided parameters.
* @param authorizedClientRemover the {@link OAuth2AuthorizedClientRemover} used for
* removing an {@link OAuth2AuthorizedClient} if the error code is one of the
* {@link #DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES}.
*/
public RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
OAuth2AuthorizedClientRemover authorizedClientRemover) {
this(authorizedClientRemover, DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES);
}
/**
* Constructs a
* {@code RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} using the
* provided parameters.
* @param authorizedClientRemover the {@link OAuth2AuthorizedClientRemover} used for
* removing an {@link OAuth2AuthorizedClient} if the error code is one of the
* {@link #removeAuthorizedClientErrorCodes}.
* @param removeAuthorizedClientErrorCodes the OAuth 2.0 error codes which will
* trigger removal of an authorized client.
* @see OAuth2ErrorCodes
*/
public RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
OAuth2AuthorizedClientRemover authorizedClientRemover, Set<String> removeAuthorizedClientErrorCodes) {
Assert.notNull(authorizedClientRemover, "authorizedClientRemover cannot be null");
Assert.notNull(removeAuthorizedClientErrorCodes, "removeAuthorizedClientErrorCodes cannot be null");
this.removeAuthorizedClientErrorCodes = Collections
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
this.delegate = authorizedClientRemover;
}
@Override
public Mono<Void> onAuthorizationFailure(OAuth2AuthorizationException authorizationException,
Authentication principal, Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) {
return this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(),
principal, attributes);
}
return Mono.empty();
}
/**
* Returns true if the given exception has an error code that indicates that the
* authorized client should be removed.
* @param authorizationException the exception that caused the authorization failure
* @return true if the given exception has an error code that indicates that the
* authorized client should be removed.
*/
private boolean hasRemovalErrorCode(OAuth2AuthorizationException authorizationException) {
return this.removeAuthorizedClientErrorCodes.contains(authorizationException.getError().getErrorCode());
}
/**
* Removes an {@link OAuth2AuthorizedClient} from a
* {@link ServerOAuth2AuthorizedClientRepository} or
* {@link ReactiveOAuth2AuthorizedClientService}.
*/
@FunctionalInterface
public interface OAuth2AuthorizedClientRemover {
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner).
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param attributes an immutable {@code Map} of extra optional attributes present
* under certain conditions. For example, this might contain a
* {@link org.springframework.web.server.ServerWebExchange ServerWebExchange} if
* the authorization was performed within the context of a
* {@code ServerWebExchange}.
* @return an empty {@link Mono} that completes after this handler has finished
* handling the event.
*/
Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
Map<String, Object> attributes);
}
}
| 6,913 | 41.944099 | 106 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.java | /*
* Copyright 2002-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.client;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
/**
* Implementations of this interface are responsible for the overall management of
* {@link OAuth2AuthorizedClient Authorized Client(s)}.
*
* <p>
* The primary responsibilities include:
* <ol>
* <li>Authorizing (or re-authorizing) an OAuth 2.0 Client by leveraging an
* {@link OAuth2AuthorizedClientProvider}(s).</li>
* <li>Delegating the persistence of an {@link OAuth2AuthorizedClient}, typically using an
* {@link OAuth2AuthorizedClientService} OR {@link OAuth2AuthorizedClientRepository}.</li>
* </ol>
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientProvider
* @see OAuth2AuthorizedClientService
* @see OAuth2AuthorizedClientRepository
*/
@FunctionalInterface
public interface OAuth2AuthorizedClientManager {
/**
* Attempt to authorize or re-authorize (if required) the {@link ClientRegistration
* client} identified by the provided
* {@link OAuth2AuthorizeRequest#getClientRegistrationId() clientRegistrationId}.
* Implementations must return {@code null} if authorization is not supported for the
* specified client, e.g. the associated {@link OAuth2AuthorizedClientProvider}(s)
* does not support the {@link ClientRegistration#getAuthorizationGrantType()
* authorization grant} type configured for the client.
*
* <p>
* In the case of re-authorization, implementations must return the provided
* {@link OAuth2AuthorizeRequest#getAuthorizedClient() authorized client} if
* re-authorization is not supported for the client OR is not required, e.g. a
* {@link OAuth2AuthorizedClient#getRefreshToken() refresh token} is not available OR
* the {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
* @param authorizeRequest the authorize request
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
* supported for the specified client
*/
@Nullable
OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest);
}
| 2,884 | 40.811594 | 90 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/JwtBearerOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2022 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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Function;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.endpoint.DefaultJwtBearerTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#JWT_BEARER jwt-bearer} grant.
*
* @author Joe Grandja
* @since 5.5
* @see OAuth2AuthorizedClientProvider
* @see DefaultJwtBearerTokenResponseClient
*/
public final class JwtBearerOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
private OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient = new DefaultJwtBearerTokenResponseClient();
private Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver = this::resolveJwtAssertion;
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns {@code null} if authorization (or re-authorization) is not
* supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
* authorization grant type} is not {@link AuthorizationGrantType#JWT_BEARER
* jwt-bearer} OR the {@link OAuth2AuthorizedClient#getAccessToken() access token} is
* not expired.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
* supported
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
return null;
}
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized but access token is NOT expired than no
// need for re-authorization
return null;
}
Jwt jwt = this.jwtAssertionResolver.apply(context);
if (jwt == null) {
return null;
}
// As per spec, in section 4.1 Using Assertions as Authorization Grants
// https://tools.ietf.org/html/rfc7521#section-4.1
//
// An assertion used in this context is generally a short-lived
// representation of the authorization grant, and authorization servers
// SHOULD NOT issue access tokens with a lifetime that exceeds the
// validity period of the assertion by a significant period. In
// practice, that will usually mean that refresh tokens are not issued
// in response to assertion grant requests, and access tokens will be
// issued with a reasonably short lifetime. Clients can refresh an
// expired access token by requesting a new one using the same
// assertion, if it is still valid, or with a new assertion.
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt);
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, jwtBearerGrantRequest);
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken());
}
private Jwt resolveJwtAssertion(OAuth2AuthorizationContext context) {
if (!(context.getPrincipal().getPrincipal() instanceof Jwt)) {
return null;
}
return (Jwt) context.getPrincipal().getPrincipal();
}
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
JwtBearerGrantRequest jwtBearerGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code jwt-bearer} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code jwt-bearer} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the resolver used for resolving the {@link Jwt} assertion.
* @param jwtAssertionResolver the resolver used for resolving the {@link Jwt}
* assertion
* @since 5.7
*/
public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver) {
Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null");
this.jwtAssertionResolver = jwtAssertionResolver;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 7,419 | 41.4 | 134 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientId.java | /*
* Copyright 2002-2019 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.client;
import java.io.Serializable;
import java.util.Objects;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* The identifier for {@link OAuth2AuthorizedClient}.
*
* @author Vedran Pavic
* @since 5.2
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientService
*/
public final class OAuth2AuthorizedClientId implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final String clientRegistrationId;
private final String principalName;
/**
* Constructs an {@code OAuth2AuthorizedClientId} using the provided parameters.
* @param clientRegistrationId the identifier for the client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
*/
public OAuth2AuthorizedClientId(String clientRegistrationId, String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
this.clientRegistrationId = clientRegistrationId;
this.principalName = principalName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OAuth2AuthorizedClientId that = (OAuth2AuthorizedClientId) obj;
return Objects.equals(this.clientRegistrationId, that.clientRegistrationId)
&& Objects.equals(this.principalName, that.principalName);
}
@Override
public int hashCode() {
return Objects.hash(this.clientRegistrationId, this.principalName);
}
}
| 2,331 | 31.388889 | 91 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientService.java | /*
* Copyright 2002-2017 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.client;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* Implementations of this interface are responsible for the management of
* {@link OAuth2AuthorizedClient Authorized Client(s)}, which provide the purpose of
* associating an {@link OAuth2AuthorizedClient#getAccessToken() Access Token} credential
* to a {@link OAuth2AuthorizedClient#getClientRegistration() Client} and Resource Owner,
* who is the {@link OAuth2AuthorizedClient#getPrincipalName() Principal} that originally
* granted the authorization.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2AuthorizedClient
* @see ClientRegistration
* @see Authentication
* @see OAuth2AccessToken
*/
public interface OAuth2AuthorizedClientService {
/**
* Returns the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User's {@code Principal} name or {@code null} if
* not available.
* @param clientRegistrationId the identifier for the client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
* @param <T> a type of OAuth2AuthorizedClient
* @return the {@link OAuth2AuthorizedClient} or {@code null} if not available
*/
<T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, String principalName);
/**
* Saves the {@link OAuth2AuthorizedClient} associating it to the provided End-User
* {@link Authentication} (Resource Owner).
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
*/
void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal);
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User's {@code Principal} name.
* @param clientRegistrationId the identifier for the client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
*/
void removeAuthorizedClient(String clientRegistrationId, String principalName);
}
| 2,910 | 41.808824 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.WebClientReactiveClientCredentialsTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.util.Assert;
/**
* An implementation of a {@link ReactiveOAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#CLIENT_CREDENTIALS client_credentials} grant.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
* @see WebClientReactiveClientCredentialsTokenResponseClient
*/
public final class ClientCredentialsReactiveOAuth2AuthorizedClientProvider
implements ReactiveOAuth2AuthorizedClientProvider {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient = new WebClientReactiveClientCredentialsTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns an empty {@code Mono} if authorization (or
* re-authorization) is not supported, e.g. the client's
* {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is
* not {@link AuthorizationGrantType#CLIENT_CREDENTIALS client_credentials} OR the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
* authorization (or re-authorization) is not supported
*/
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) {
return Mono.empty();
}
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized but access token is NOT expired than no
// need for re-authorization
return Mono.empty();
}
// As per spec, in section 4.4.3 Access Token Response
// https://tools.ietf.org/html/rfc6749#section-4.4.3
// A refresh token SHOULD NOT be included.
//
// Therefore, renewing an expired access token (re-authorization)
// is the same as acquiring a new access token (authorization).
return Mono.just(new OAuth2ClientCredentialsGrantRequest(clientRegistration))
.flatMap(this.accessTokenResponseClient::getTokenResponse)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(),
ex))
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken()));
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code client_credentials} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code client_credentials} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 5,959 | 42.823529 | 174 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ClientAuthorizationException.java | /*
* Copyright 2002-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.client;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.util.Assert;
/**
* This exception is thrown on the client side when an attempt to authenticate or
* authorize an OAuth 2.0 client fails.
*
* @author Phil Clay
* @since 5.3
* @see OAuth2AuthorizedClient
*/
public class ClientAuthorizationException extends OAuth2AuthorizationException {
private final String clientRegistrationId;
/**
* Constructs a {@code ClientAuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param clientRegistrationId the identifier for the client's registration
*/
public ClientAuthorizationException(OAuth2Error error, String clientRegistrationId) {
this(error, clientRegistrationId, error.toString());
}
/**
* Constructs a {@code ClientAuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param clientRegistrationId the identifier for the client's registration
* @param message the exception message
*/
public ClientAuthorizationException(OAuth2Error error, String clientRegistrationId, String message) {
super(error, message);
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
this.clientRegistrationId = clientRegistrationId;
}
/**
* Constructs a {@code ClientAuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param clientRegistrationId the identifier for the client's registration
* @param cause the root cause
*/
public ClientAuthorizationException(OAuth2Error error, String clientRegistrationId, Throwable cause) {
this(error, clientRegistrationId, error.toString(), cause);
}
/**
* Constructs a {@code ClientAuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param clientRegistrationId the identifier for the client's registration
* @param message the exception message
* @param cause the root cause
*/
public ClientAuthorizationException(OAuth2Error error, String clientRegistrationId, String message,
Throwable cause) {
super(error, message, cause);
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
this.clientRegistrationId = clientRegistrationId;
}
/**
* Returns the identifier for the client's registration.
* @return the identifier for the client's registration
*/
public String getClientRegistrationId() {
return this.clientRegistrationId;
}
}
| 3,325 | 36.370787 | 103 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/R2dbcReactiveOAuth2AuthorizedClientService.java | /*
* Copyright 2002-2022 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.client;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import reactor.core.publisher.Mono;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.r2dbc.core.DatabaseClient.GenericExecuteSpec;
import org.springframework.r2dbc.core.Parameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* A R2DBC implementation of {@link ReactiveOAuth2AuthorizedClientService} that uses a
* {@link DatabaseClient} for {@link OAuth2AuthorizedClient} persistence.
*
* <p>
* <b>NOTE:</b> This {@code ReactiveOAuth2AuthorizedClientService} depends on the table
* definition described in
* "classpath:org/springframework/security/oauth2/client/oauth2-client-schema.sql" and
* therefore MUST be defined in the database schema.
*
* @author Ovidiu Popa
* @since 5.5
* @see ReactiveOAuth2AuthorizedClientService
* @see OAuth2AuthorizedClient
* @see DatabaseClient
*
*/
public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth2AuthorizedClientService {
// @formatter:off
private static final String COLUMN_NAMES =
"client_registration_id, " +
"principal_name, " +
"access_token_type, " +
"access_token_value, " +
"access_token_issued_at, " +
"access_token_expires_at, " +
"access_token_scopes, " +
"refresh_token_value, " +
"refresh_token_issued_at";
// @formatter:on
private static final String TABLE_NAME = "oauth2_authorized_client";
private static final String PK_FILTER = "client_registration_id = :clientRegistrationId AND principal_name = :principalName";
// @formatter:off
private static final String LOAD_AUTHORIZED_CLIENT_SQL = "SELECT " + COLUMN_NAMES + " FROM " + TABLE_NAME
+ " WHERE " + PK_FILTER;
// @formatter:on
// @formatter:off
private static final String SAVE_AUTHORIZED_CLIENT_SQL = "INSERT INTO " + TABLE_NAME + " (" + COLUMN_NAMES + ")" +
"VALUES (:clientRegistrationId, :principalName, :accessTokenType, :accessTokenValue," +
" :accessTokenIssuedAt, :accessTokenExpiresAt, :accessTokenScopes, :refreshTokenValue," +
" :refreshTokenIssuedAt)";
// @formatter:on
private static final String REMOVE_AUTHORIZED_CLIENT_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + PK_FILTER;
// @formatter:off
private static final String UPDATE_AUTHORIZED_CLIENT_SQL = "UPDATE " + TABLE_NAME +
" SET access_token_type = :accessTokenType, " +
" access_token_value = :accessTokenValue, " +
" access_token_issued_at = :accessTokenIssuedAt," +
" access_token_expires_at = :accessTokenExpiresAt, " +
" access_token_scopes = :accessTokenScopes," +
" refresh_token_value = :refreshTokenValue, " +
" refresh_token_issued_at = :refreshTokenIssuedAt" +
" WHERE " +
PK_FILTER;
// @formatter:on
protected final DatabaseClient databaseClient;
protected final ReactiveClientRegistrationRepository clientRegistrationRepository;
protected Function<OAuth2AuthorizedClientHolder, Map<String, Parameter>> authorizedClientParametersMapper;
protected BiFunction<Row, RowMetadata, OAuth2AuthorizedClientHolder> authorizedClientRowMapper;
/**
* Constructs a {@code R2dbcReactiveOAuth2AuthorizedClientService} using the provided
* parameters.
* @param databaseClient the database client
* @param clientRegistrationRepository the repository of client registrations
*/
public R2dbcReactiveOAuth2AuthorizedClientService(DatabaseClient databaseClient,
ReactiveClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(databaseClient, "databaseClient cannot be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.databaseClient = databaseClient;
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientParametersMapper = new OAuth2AuthorizedClientParametersMapper();
this.authorizedClientRowMapper = new OAuth2AuthorizedClientRowMapper();
}
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (Mono<T>) this.databaseClient.sql(LOAD_AUTHORIZED_CLIENT_SQL)
.bind("clientRegistrationId", clientRegistrationId).bind("principalName", principalName)
.map(this.authorizedClientRowMapper).first().flatMap(this::getAuthorizedClient);
}
private Mono<OAuth2AuthorizedClient> getAuthorizedClient(OAuth2AuthorizedClientHolder authorizedClientHolder) {
return this.clientRegistrationRepository.findByRegistrationId(authorizedClientHolder.getClientRegistrationId())
.switchIfEmpty(
Mono.error(dataRetrievalFailureException(authorizedClientHolder.getClientRegistrationId())))
.map((clientRegistration) -> new OAuth2AuthorizedClient(clientRegistration,
authorizedClientHolder.getPrincipalName(), authorizedClientHolder.getAccessToken(),
authorizedClientHolder.getRefreshToken()));
}
private static Throwable dataRetrievalFailureException(String clientRegistrationId) {
return new DataRetrievalFailureException("The ClientRegistration with id '" + clientRegistrationId
+ "' exists in the data source, however, it was not found in the ReactiveClientRegistrationRepository.");
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
return this
.loadAuthorizedClient(authorizedClient.getClientRegistration().getRegistrationId(), principal.getName())
.flatMap((dbAuthorizedClient) -> updateAuthorizedClient(authorizedClient, principal))
.switchIfEmpty(Mono.defer(() -> insertAuthorizedClient(authorizedClient, principal))).then();
}
private Mono<Long> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
GenericExecuteSpec executeSpec = this.databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL);
for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) {
executeSpec = executeSpec.bind(entry.getKey(), entry.getValue());
}
return executeSpec.fetch().rowsUpdated();
}
private Mono<Long> insertAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
GenericExecuteSpec executeSpec = this.databaseClient.sql(SAVE_AUTHORIZED_CLIENT_SQL);
for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) {
executeSpec = executeSpec.bind(entry.getKey(), entry.getValue());
}
return executeSpec.fetch().rowsUpdated();
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return this.databaseClient.sql(REMOVE_AUTHORIZED_CLIENT_SQL).bind("clientRegistrationId", clientRegistrationId)
.bind("principalName", principalName).then();
}
/**
* Sets the {@code Function} used for mapping {@link OAuth2AuthorizedClientHolder} to
* a {@code Map} of {@link String} and {@link Parameter}. The default is
* {@link OAuth2AuthorizedClientParametersMapper}.
* @param authorizedClientParametersMapper the {@code Function} used for mapping
* {@link OAuth2AuthorizedClientHolder} to a {@code Map} of {@link String} and
* {@link Parameter}
*/
public final void setAuthorizedClientParametersMapper(
Function<OAuth2AuthorizedClientHolder, Map<String, Parameter>> authorizedClientParametersMapper) {
Assert.notNull(authorizedClientParametersMapper, "authorizedClientParametersMapper cannot be null");
this.authorizedClientParametersMapper = authorizedClientParametersMapper;
}
/**
* Sets the {@link BiFunction} used for mapping the current {@code io.r2dbc.spi.Row}
* to {@link OAuth2AuthorizedClientHolder}. The default is
* {@link OAuth2AuthorizedClientRowMapper}.
* @param authorizedClientRowMapper the {@link BiFunction} used for mapping the
* current {@code io.r2dbc.spi.Row} to {@link OAuth2AuthorizedClientHolder}
*/
public final void setAuthorizedClientRowMapper(
BiFunction<Row, RowMetadata, OAuth2AuthorizedClientHolder> authorizedClientRowMapper) {
Assert.notNull(authorizedClientRowMapper, "authorizedClientRowMapper cannot be null");
this.authorizedClientRowMapper = authorizedClientRowMapper;
}
/**
* A holder for {@link OAuth2AuthorizedClient} data and End-User
* {@link Authentication} (Resource Owner).
*/
public static final class OAuth2AuthorizedClientHolder {
private final String clientRegistrationId;
private final String principalName;
private final OAuth2AccessToken accessToken;
private final OAuth2RefreshToken refreshToken;
/**
* Constructs an {@code OAuth2AuthorizedClientHolder} using the provided
* parameters.
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
*/
public OAuth2AuthorizedClientHolder(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
this.clientRegistrationId = authorizedClient.getClientRegistration().getRegistrationId();
this.principalName = principal.getName();
this.accessToken = authorizedClient.getAccessToken();
this.refreshToken = authorizedClient.getRefreshToken();
}
/**
* Constructs an {@code OAuth2AuthorizedClientHolder} using the provided
* parameters.
* @param clientRegistrationId the client registration id
* @param principalName the principal name of the End-User (Resource Owner)
* @param accessToken the access token
* @param refreshToken the refresh token
*/
public OAuth2AuthorizedClientHolder(String clientRegistrationId, String principalName,
OAuth2AccessToken accessToken, OAuth2RefreshToken refreshToken) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
Assert.notNull(accessToken, "accessToken cannot be null");
this.clientRegistrationId = clientRegistrationId;
this.principalName = principalName;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
public String getClientRegistrationId() {
return this.clientRegistrationId;
}
public String getPrincipalName() {
return this.principalName;
}
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
public OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
}
/**
* The default {@code Function} that maps {@link OAuth2AuthorizedClientHolder} to a
* {@code Map} of {@link String} and {@link Parameter}.
*/
public static class OAuth2AuthorizedClientParametersMapper
implements Function<OAuth2AuthorizedClientHolder, Map<String, Parameter>> {
@Override
public Map<String, Parameter> apply(OAuth2AuthorizedClientHolder authorizedClientHolder) {
final Map<String, Parameter> parameters = new HashMap<>();
final OAuth2AccessToken accessToken = authorizedClientHolder.getAccessToken();
final OAuth2RefreshToken refreshToken = authorizedClientHolder.getRefreshToken();
parameters.put("clientRegistrationId",
Parameter.fromOrEmpty(authorizedClientHolder.getClientRegistrationId(), String.class));
parameters.put("principalName",
Parameter.fromOrEmpty(authorizedClientHolder.getPrincipalName(), String.class));
parameters.put("accessTokenType",
Parameter.fromOrEmpty(accessToken.getTokenType().getValue(), String.class));
parameters.put("accessTokenValue", Parameter.fromOrEmpty(
ByteBuffer.wrap(accessToken.getTokenValue().getBytes(StandardCharsets.UTF_8)), ByteBuffer.class));
parameters.put("accessTokenIssuedAt", Parameter.fromOrEmpty(
LocalDateTime.ofInstant(accessToken.getIssuedAt(), ZoneOffset.UTC), LocalDateTime.class));
parameters.put("accessTokenExpiresAt", Parameter.fromOrEmpty(
LocalDateTime.ofInstant(accessToken.getExpiresAt(), ZoneOffset.UTC), LocalDateTime.class));
String accessTokenScopes = null;
if (!CollectionUtils.isEmpty(accessToken.getScopes())) {
accessTokenScopes = StringUtils.collectionToDelimitedString(accessToken.getScopes(), ",");
}
parameters.put("accessTokenScopes", Parameter.fromOrEmpty(accessTokenScopes, String.class));
ByteBuffer refreshTokenValue = null;
LocalDateTime refreshTokenIssuedAt = null;
if (refreshToken != null) {
refreshTokenValue = ByteBuffer.wrap(refreshToken.getTokenValue().getBytes(StandardCharsets.UTF_8));
if (refreshToken.getIssuedAt() != null) {
refreshTokenIssuedAt = LocalDateTime.ofInstant(refreshToken.getIssuedAt(), ZoneOffset.UTC);
}
}
parameters.put("refreshTokenValue", Parameter.fromOrEmpty(refreshTokenValue, ByteBuffer.class));
parameters.put("refreshTokenIssuedAt", Parameter.fromOrEmpty(refreshTokenIssuedAt, LocalDateTime.class));
return parameters;
}
}
/**
* The default {@link BiFunction} that maps the current {@code io.r2dbc.spi.Row} to a
* {@link OAuth2AuthorizedClientHolder}.
*/
public static class OAuth2AuthorizedClientRowMapper
implements BiFunction<Row, RowMetadata, OAuth2AuthorizedClientHolder> {
@Override
public OAuth2AuthorizedClientHolder apply(Row row, RowMetadata rowMetadata) {
String dbClientRegistrationId = row.get("client_registration_id", String.class);
OAuth2AccessToken.TokenType tokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue()
.equalsIgnoreCase(row.get("access_token_type", String.class))) {
tokenType = OAuth2AccessToken.TokenType.BEARER;
}
String tokenValue = new String(row.get("access_token_value", ByteBuffer.class).array(),
StandardCharsets.UTF_8);
Instant issuedAt = row.get("access_token_issued_at", LocalDateTime.class).toInstant(ZoneOffset.UTC);
Instant expiresAt = row.get("access_token_expires_at", LocalDateTime.class).toInstant(ZoneOffset.UTC);
Set<String> scopes = Collections.emptySet();
String accessTokenScopes = row.get("access_token_scopes", String.class);
if (accessTokenScopes != null) {
scopes = StringUtils.commaDelimitedListToSet(accessTokenScopes);
}
final OAuth2AccessToken accessToken = new OAuth2AccessToken(tokenType, tokenValue, issuedAt, expiresAt,
scopes);
OAuth2RefreshToken refreshToken = null;
ByteBuffer refreshTokenValue = row.get("refresh_token_value", ByteBuffer.class);
if (refreshTokenValue != null) {
tokenValue = new String(refreshTokenValue.array(), StandardCharsets.UTF_8);
issuedAt = null;
LocalDateTime refreshTokenIssuedAt = row.get("refresh_token_issued_at", LocalDateTime.class);
if (refreshTokenIssuedAt != null) {
issuedAt = refreshTokenIssuedAt.toInstant(ZoneOffset.UTC);
}
refreshToken = new OAuth2RefreshToken(tokenValue, issuedAt);
}
String dbPrincipalName = row.get("principal_name", String.class);
return new OAuth2AuthorizedClientHolder(dbClientRegistrationId, dbPrincipalName, accessToken, refreshToken);
}
}
}
| 16,953 | 42.695876 | 126 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#CLIENT_CREDENTIALS client_credentials} grant.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
* @see DefaultClientCredentialsTokenResponseClient
*/
public final class ClientCredentialsOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
private OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns {@code null} if authorization (or re-authorization) is not
* supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
* authorization grant type} is not {@link AuthorizationGrantType#CLIENT_CREDENTIALS
* client_credentials} OR the {@link OAuth2AuthorizedClient#getAccessToken() access
* token} is not expired.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization (or
* re-authorization) is not supported
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) {
return null;
}
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized but access token is NOT expired than no
// need for re-authorization
return null;
}
// As per spec, in section 4.4.3 Access Token Response
// https://tools.ietf.org/html/rfc6749#section-4.4.3
// A refresh token SHOULD NOT be included.
//
// Therefore, renewing an expired access token (re-authorization)
// is the same as acquiring a new access token (authorization).
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, clientCredentialsGrantRequest);
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken());
}
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code client_credentials} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code client_credentials} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 6,268 | 42.534722 | 156 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientService.java | /*
* Copyright 2002-2019 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.client;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.util.Assert;
/**
* An {@link OAuth2AuthorizedClientService} that stores {@link OAuth2AuthorizedClient
* Authorized Client(s)} in-memory.
*
* @author Joe Grandja
* @author Vedran Pavic
* @since 5.0
* @see OAuth2AuthorizedClientService
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientId
* @see ClientRegistration
* @see Authentication
*/
public final class InMemoryOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService {
private final Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients;
private final ClientRegistrationRepository clientRegistrationRepository;
/**
* Constructs an {@code InMemoryOAuth2AuthorizedClientService} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
*/
public InMemoryOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClients = new ConcurrentHashMap<>();
}
/**
* Constructs an {@code InMemoryOAuth2AuthorizedClientService} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClients the initial {@code Map} of authorized client(s) keyed by
* {@link OAuth2AuthorizedClientId}
* @since 5.2
*/
public InMemoryOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository,
Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notEmpty(authorizedClients, "authorizedClients cannot be empty");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClients = new ConcurrentHashMap<>(authorizedClients);
}
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
ClientRegistration registration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
if (registration == null) {
return null;
}
return (T) this.authorizedClients.get(new OAuth2AuthorizedClientId(clientRegistrationId, principalName));
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
this.authorizedClients.put(new OAuth2AuthorizedClientId(
authorizedClient.getClientRegistration().getRegistrationId(), principal.getName()), authorizedClient);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
ClientRegistration registration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
if (registration != null) {
this.authorizedClients.remove(new OAuth2AuthorizedClientId(clientRegistrationId, principalName));
}
}
}
| 4,469 | 41.571429 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContext.java | /*
* Copyright 2002-2019 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.client;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* A context that holds authorization-specific state and is used by an
* {@link OAuth2AuthorizedClientProvider} when attempting to authorize (or re-authorize)
* an OAuth 2.0 Client.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
*/
public final class OAuth2AuthorizationContext {
/**
* The name of the {@link #getAttribute(String) attribute} in the context associated
* to the value for the "request scope(s)". The value of the attribute is a
* {@code String[]} of scope(s) to be requested by the {@link #getClientRegistration()
* client}.
*/
public static final String REQUEST_SCOPE_ATTRIBUTE_NAME = OAuth2AuthorizationContext.class.getName()
.concat(".REQUEST_SCOPE");
/**
* The name of the {@link #getAttribute(String) attribute} in the context associated
* to the value for the resource owner's username.
*/
public static final String USERNAME_ATTRIBUTE_NAME = OAuth2AuthorizationContext.class.getName().concat(".USERNAME");
/**
* The name of the {@link #getAttribute(String) attribute} in the context associated
* to the value for the resource owner's password.
*/
public static final String PASSWORD_ATTRIBUTE_NAME = OAuth2AuthorizationContext.class.getName().concat(".PASSWORD");
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
private Map<String, Object> attributes;
private OAuth2AuthorizationContext() {
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the {@link OAuth2AuthorizedClient authorized client} or {@code null} if the
* {@link #withClientRegistration(ClientRegistration) client registration} was
* supplied.
* @return the {@link OAuth2AuthorizedClient} or {@code null} if the client
* registration was supplied
*/
@Nullable
public OAuth2AuthorizedClient getAuthorizedClient() {
return this.authorizedClient;
}
/**
* Returns the {@code Principal} (to be) associated to the authorized client.
* @return the {@code Principal} (to be) associated to the authorized client
*/
public Authentication getPrincipal() {
return this.principal;
}
/**
* Returns the attributes associated to the context.
* @return a {@code Map} of the attributes associated to the context
*/
public Map<String, Object> getAttributes() {
return this.attributes;
}
/**
* Returns the value of an attribute associated to the context or {@code null} if not
* available.
* @param name the name of the attribute
* @param <T> the type of the attribute
* @return the value of the attribute associated to the context
*/
@Nullable
@SuppressWarnings("unchecked")
public <T> T getAttribute(String name) {
return (T) this.getAttributes().get(name);
}
/**
* Returns a new {@link Builder} initialized with the {@link ClientRegistration}.
* @param clientRegistration the {@link ClientRegistration client registration}
* @return the {@link Builder}
*/
public static Builder withClientRegistration(ClientRegistration clientRegistration) {
return new Builder(clientRegistration);
}
/**
* Returns a new {@link Builder} initialized with the {@link OAuth2AuthorizedClient}.
* @param authorizedClient the {@link OAuth2AuthorizedClient authorized client}
* @return the {@link Builder}
*/
public static Builder withAuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
return new Builder(authorizedClient);
}
/**
* A builder for {@link OAuth2AuthorizationContext}.
*/
public static final class Builder {
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
private Map<String, Object> attributes;
private Builder(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.clientRegistration = clientRegistration;
}
private Builder(OAuth2AuthorizedClient authorizedClient) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
this.authorizedClient = authorizedClient;
}
/**
* Sets the {@code Principal} (to be) associated to the authorized client.
* @param principal the {@code Principal} (to be) associated to the authorized
* client
* @return the {@link Builder}
*/
public Builder principal(Authentication principal) {
this.principal = principal;
return this;
}
/**
* Provides a {@link Consumer} access to the attributes associated to the context.
* @param attributesConsumer a {@link Consumer} of the attributes associated to
* the context
* @return the {@link OAuth2AuthorizeRequest.Builder}
*/
public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
attributesConsumer.accept(this.attributes);
return this;
}
/**
* Sets an attribute associated to the context.
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder}
*/
public Builder attribute(String name, Object value) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.put(name, value);
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationContext}.
* @return a {@link OAuth2AuthorizationContext}
*/
public OAuth2AuthorizationContext build() {
Assert.notNull(this.principal, "principal cannot be null");
OAuth2AuthorizationContext context = new OAuth2AuthorizationContext();
if (this.authorizedClient != null) {
context.clientRegistration = this.authorizedClient.getClientRegistration();
context.authorizedClient = this.authorizedClient;
}
else {
context.clientRegistration = this.clientRegistration;
}
context.principal = this.principal;
context.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes)
? Collections.emptyMap() : new LinkedHashMap<>(this.attributes));
return context;
}
}
}
| 7,322 | 31.402655 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClient.java | /*
* Copyright 2002-2018 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.client;
import java.io.Serializable;
import org.springframework.lang.Nullable;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.util.Assert;
/**
* A representation of an OAuth 2.0 "Authorized Client".
* <p>
* A client is considered "authorized" when the End-User (Resource Owner) has
* granted authorization to the client to access it's protected resources.
* <p>
* This class associates the {@link #getClientRegistration() Client} to the
* {@link #getAccessToken() Access Token} granted/authorized by the
* {@link #getPrincipalName() Resource Owner}.
*
* @author Joe Grandja
* @since 5.0
* @see ClientRegistration
* @see OAuth2AccessToken
* @see OAuth2RefreshToken
*/
public class OAuth2AuthorizedClient implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final ClientRegistration clientRegistration;
private final String principalName;
private final OAuth2AccessToken accessToken;
private final OAuth2RefreshToken refreshToken;
/**
* Constructs an {@code OAuth2AuthorizedClient} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
* @param accessToken the access token credential granted
*/
public OAuth2AuthorizedClient(ClientRegistration clientRegistration, String principalName,
OAuth2AccessToken accessToken) {
this(clientRegistration, principalName, accessToken, null);
}
/**
* Constructs an {@code OAuth2AuthorizedClient} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
* @param accessToken the access token credential granted
* @param refreshToken the refresh token credential granted
*/
public OAuth2AuthorizedClient(ClientRegistration clientRegistration, String principalName,
OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
Assert.hasText(principalName, "principalName cannot be empty");
Assert.notNull(accessToken, "accessToken cannot be null");
this.clientRegistration = clientRegistration;
this.principalName = principalName;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
/**
* Returns the authorized client's {@link ClientRegistration registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the End-User's {@code Principal} name.
* @return the End-User's {@code Principal} name
*/
public String getPrincipalName() {
return this.principalName;
}
/**
* Returns the {@link OAuth2AccessToken access token} credential granted.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token} credential granted.
* @return the {@link OAuth2RefreshToken}
* @since 5.1
*/
public @Nullable OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
}
| 4,213 | 34.411765 | 91 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java | /*
* Copyright 2002-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.oauth2.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.util.Assert;
/**
* A builder that builds a {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
* composed of one or more {@link ReactiveOAuth2AuthorizedClientProvider}(s) that
* implement specific authorization grants. The supported authorization grants are
* {@link #authorizationCode() authorization_code}, {@link #refreshToken() refresh_token},
* {@link #clientCredentials() client_credentials} and {@link #password() password}. In
* addition to the standard authorization grants, an implementation of an extension grant
* may be supplied via {@link #provider(ReactiveOAuth2AuthorizedClientProvider)}.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientProvider
* @see AuthorizationCodeReactiveOAuth2AuthorizedClientProvider
* @see RefreshTokenReactiveOAuth2AuthorizedClientProvider
* @see ClientCredentialsReactiveOAuth2AuthorizedClientProvider
* @see PasswordReactiveOAuth2AuthorizedClientProvider
* @see DelegatingReactiveOAuth2AuthorizedClientProvider
*/
public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
private final Map<Class<?>, Builder> builders = new LinkedHashMap<>();
private ReactiveOAuth2AuthorizedClientProviderBuilder() {
}
/**
* Returns a new {@link ReactiveOAuth2AuthorizedClientProviderBuilder} for configuring
* the supported authorization grant(s).
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public static ReactiveOAuth2AuthorizedClientProviderBuilder builder() {
return new ReactiveOAuth2AuthorizedClientProviderBuilder();
}
/**
* Configures a {@link ReactiveOAuth2AuthorizedClientProvider} to be composed with the
* {@link DelegatingReactiveOAuth2AuthorizedClientProvider}. This may be used for
* implementations of extension authorization grants.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder provider(ReactiveOAuth2AuthorizedClientProvider provider) {
Assert.notNull(provider, "provider cannot be null");
this.builders.computeIfAbsent(provider.getClass(), (k) -> () -> provider);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code authorization_code} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder authorizationCode() {
this.builders.computeIfAbsent(AuthorizationCodeReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new AuthorizationCodeGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken() {
this.builders.computeIfAbsent(RefreshTokenReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new RefreshTokenGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @param builderConsumer a {@code Consumer} of {@link RefreshTokenGrantBuilder} used
* for further configuration
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken(
Consumer<RefreshTokenGrantBuilder> builderConsumer) {
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders.computeIfAbsent(
RefreshTokenReactiveOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
builderConsumer.accept(builder);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder clientCredentials() {
this.builders.computeIfAbsent(ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new ClientCredentialsGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @param builderConsumer a {@code Consumer} of {@link ClientCredentialsGrantBuilder}
* used for further configuration
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder clientCredentials(
Consumer<ClientCredentialsGrantBuilder> builderConsumer) {
ClientCredentialsGrantBuilder builder = (ClientCredentialsGrantBuilder) this.builders.computeIfAbsent(
ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new ClientCredentialsGrantBuilder());
builderConsumer.accept(builder);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code password} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use
* of the Resource Owner Password Credentials grant. See reference
* <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public ReactiveOAuth2AuthorizedClientProviderBuilder password() {
this.builders.computeIfAbsent(PasswordReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new PasswordGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code password} grant.
* @param builderConsumer a {@code Consumer} of {@link PasswordGrantBuilder} used for
* further configuration
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use
* of the Resource Owner Password Credentials grant. See reference
* <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public ReactiveOAuth2AuthorizedClientProviderBuilder password(Consumer<PasswordGrantBuilder> builderConsumer) {
PasswordGrantBuilder builder = (PasswordGrantBuilder) this.builders.computeIfAbsent(
PasswordReactiveOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
builderConsumer.accept(builder);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Builds an instance of {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
* composed of one or more {@link ReactiveOAuth2AuthorizedClientProvider}(s).
* @return the {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
*/
public ReactiveOAuth2AuthorizedClientProvider build() {
List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders = this.builders.values().stream()
.map(Builder::build).collect(Collectors.toList());
return new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProviders);
}
interface Builder {
ReactiveOAuth2AuthorizedClientProvider build();
}
/**
* A builder for the {@code authorization_code} grant.
*/
public final class AuthorizationCodeGrantBuilder implements Builder {
private AuthorizationCodeGrantBuilder() {
}
/**
* Builds an instance of
* {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}.
* @return the {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}
*/
@Override
public ReactiveOAuth2AuthorizedClientProvider build() {
return new AuthorizationCodeReactiveOAuth2AuthorizedClientProvider();
}
}
/**
* A builder for the {@code client_credentials} grant.
*/
public final class ClientCredentialsGrantBuilder implements Builder {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private ClientCredentialsGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link ClientCredentialsGrantBuilder}
*/
public ClientCredentialsGrantBuilder accessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link ClientCredentialsGrantBuilder}
* @see ClientCredentialsReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public ClientCredentialsGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link ClientCredentialsGrantBuilder}
*/
public ClientCredentialsGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of
* {@link ClientCredentialsReactiveOAuth2AuthorizedClientProvider}.
* @return the {@link ClientCredentialsReactiveOAuth2AuthorizedClientProvider}
*/
@Override
public ReactiveOAuth2AuthorizedClientProvider build() {
ClientCredentialsReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new ClientCredentialsReactiveOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
/**
* A builder for the {@code password} grant.
*/
public final class PasswordGrantBuilder implements Builder {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private PasswordGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link PasswordGrantBuilder}
*/
public PasswordGrantBuilder accessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link PasswordGrantBuilder}
* @see PasswordReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public PasswordGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link PasswordGrantBuilder}
*/
public PasswordGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of {@link PasswordReactiveOAuth2AuthorizedClientProvider}.
* @return the {@link PasswordReactiveOAuth2AuthorizedClientProvider}
*/
@Override
public ReactiveOAuth2AuthorizedClientProvider build() {
PasswordReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new PasswordReactiveOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
/**
* A builder for the {@code refresh_token} grant.
*/
public final class RefreshTokenGrantBuilder implements Builder {
private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private RefreshTokenGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link RefreshTokenGrantBuilder}
*/
public RefreshTokenGrantBuilder accessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link RefreshTokenGrantBuilder}
* @see RefreshTokenReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link RefreshTokenGrantBuilder}
*/
public RefreshTokenGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of
* {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}.
* @return the {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}
*/
@Override
public ReactiveOAuth2AuthorizedClientProvider build() {
RefreshTokenReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenReactiveOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
}
| 16,541 | 37.203233 | 148 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientService.java | /*
* Copyright 2002-2018 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.client;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* Implementations of this interface are responsible for the management of
* {@link OAuth2AuthorizedClient Authorized Client(s)}, which provide the purpose of
* associating an {@link OAuth2AuthorizedClient#getAccessToken() Access Token} credential
* to a {@link OAuth2AuthorizedClient#getClientRegistration() Client} and Resource Owner,
* who is the {@link OAuth2AuthorizedClient#getPrincipalName() Principal} that originally
* granted the authorization.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizedClient
* @see ClientRegistration
* @see Authentication
* @see OAuth2AccessToken
*/
public interface ReactiveOAuth2AuthorizedClientService {
/**
* Returns the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User's {@code Principal} name or {@code null} if
* not available.
* @param clientRegistrationId the identifier for the client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
* @param <T> a type of OAuth2AuthorizedClient
* @return the {@link OAuth2AuthorizedClient} or {@code null} if not available
*/
<T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, String principalName);
/**
* Saves the {@link OAuth2AuthorizedClient} associating it to the provided End-User
* {@link Authentication} (Resource Owner).
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
*/
Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal);
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User's {@code Principal} name.
* @param clientRegistrationId the identifier for the client's registration
* @param principalName the name of the End-User {@code Principal} (Resource Owner)
*/
Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName);
}
| 2,971 | 41.457143 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequest.java | /*
* Copyright 2002-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.client;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Represents a request the {@link OAuth2AuthorizedClientManager} uses to
* {@link OAuth2AuthorizedClientManager#authorize(OAuth2AuthorizeRequest) authorize} (or
* re-authorize) the {@link ClientRegistration client} identified by the provided
* {@link #getClientRegistrationId() clientRegistrationId}.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientManager
*/
public final class OAuth2AuthorizeRequest {
private String clientRegistrationId;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
private Map<String, Object> attributes;
private OAuth2AuthorizeRequest() {
}
/**
* Returns the identifier for the {@link ClientRegistration client registration}.
* @return the identifier for the client registration
*/
public String getClientRegistrationId() {
return this.clientRegistrationId;
}
/**
* Returns the {@link OAuth2AuthorizedClient authorized client} or {@code null} if it
* was not provided.
* @return the {@link OAuth2AuthorizedClient} or {@code null} if it was not provided
*/
@Nullable
public OAuth2AuthorizedClient getAuthorizedClient() {
return this.authorizedClient;
}
/**
* Returns the {@code Principal} (to be) associated to the authorized client.
* @return the {@code Principal} (to be) associated to the authorized client
*/
public Authentication getPrincipal() {
return this.principal;
}
/**
* Returns the attributes associated to the request.
* @return a {@code Map} of the attributes associated to the request
*/
public Map<String, Object> getAttributes() {
return this.attributes;
}
/**
* Returns the value of an attribute associated to the request or {@code null} if not
* available.
* @param name the name of the attribute
* @param <T> the type of the attribute
* @return the value of the attribute associated to the request
*/
@Nullable
@SuppressWarnings("unchecked")
public <T> T getAttribute(String name) {
return (T) this.getAttributes().get(name);
}
/**
* Returns a new {@link Builder} initialized with the identifier for the
* {@link ClientRegistration client registration}.
* @param clientRegistrationId the identifier for the {@link ClientRegistration client
* registration}
* @return the {@link Builder}
*/
public static Builder withClientRegistrationId(String clientRegistrationId) {
return new Builder(clientRegistrationId);
}
/**
* Returns a new {@link Builder} initialized with the {@link OAuth2AuthorizedClient
* authorized client}.
* @param authorizedClient the {@link OAuth2AuthorizedClient authorized client}
* @return the {@link Builder}
*/
public static Builder withAuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
return new Builder(authorizedClient);
}
/**
* A builder for {@link OAuth2AuthorizeRequest}.
*/
public static final class Builder {
private String clientRegistrationId;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
private Map<String, Object> attributes;
private Builder(String clientRegistrationId) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
this.clientRegistrationId = clientRegistrationId;
}
private Builder(OAuth2AuthorizedClient authorizedClient) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
this.authorizedClient = authorizedClient;
}
/**
* Sets the name of the {@code Principal} (to be) associated to the authorized
* client.
* @param principalName the name of the {@code Principal} (to be) associated to
* the authorized client
* @return the {@link Builder}
* @since 5.3
*/
public Builder principal(String principalName) {
return principal(createAuthentication(principalName));
}
private static Authentication createAuthentication(final String principalName) {
Assert.hasText(principalName, "principalName cannot be empty");
return new AbstractAuthenticationToken(null) {
@Override
public Object getCredentials() {
return "";
}
@Override
public Object getPrincipal() {
return principalName;
}
};
}
/**
* Sets the {@code Principal} (to be) associated to the authorized client.
* @param principal the {@code Principal} (to be) associated to the authorized
* client
* @return the {@link Builder}
*/
public Builder principal(Authentication principal) {
this.principal = principal;
return this;
}
/**
* Provides a {@link Consumer} access to the attributes associated to the request.
* @param attributesConsumer a {@link Consumer} of the attributes associated to
* the request
* @return the {@link Builder}
*/
public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
attributesConsumer.accept(this.attributes);
return this;
}
/**
* Sets an attribute associated to the request.
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder}
*/
public Builder attribute(String name, Object value) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.put(name, value);
return this;
}
/**
* Builds a new {@link OAuth2AuthorizeRequest}.
* @return a {@link OAuth2AuthorizeRequest}
*/
public OAuth2AuthorizeRequest build() {
Assert.notNull(this.principal, "principal cannot be null");
OAuth2AuthorizeRequest authorizeRequest = new OAuth2AuthorizeRequest();
if (this.authorizedClient != null) {
authorizeRequest.clientRegistrationId = this.authorizedClient.getClientRegistration()
.getRegistrationId();
authorizeRequest.authorizedClient = this.authorizedClient;
}
else {
authorizeRequest.clientRegistrationId = this.clientRegistrationId;
}
authorizeRequest.principal = this.principal;
authorizeRequest.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes)
? Collections.emptyMap() : new LinkedHashMap<>(this.attributes));
return authorizeRequest;
}
}
}
| 7,361 | 29.932773 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2019 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.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} that simply delegates to
* it's internal {@code List} of {@link OAuth2AuthorizedClientProvider}(s).
* <p>
* Each provider is given a chance to
* {@link OAuth2AuthorizedClientProvider#authorize(OAuth2AuthorizationContext) authorize}
* the {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* context with the first {@code non-null} {@link OAuth2AuthorizedClient} being returned.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
*/
public final class DelegatingOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
private final List<OAuth2AuthorizedClientProvider> authorizedClientProviders;
/**
* Constructs a {@code DelegatingOAuth2AuthorizedClientProvider} using the provided
* parameters.
* @param authorizedClientProviders a list of
* {@link OAuth2AuthorizedClientProvider}(s)
*/
public DelegatingOAuth2AuthorizedClientProvider(OAuth2AuthorizedClientProvider... authorizedClientProviders) {
Assert.notEmpty(authorizedClientProviders, "authorizedClientProviders cannot be empty");
this.authorizedClientProviders = Collections.unmodifiableList(Arrays.asList(authorizedClientProviders));
}
/**
* Constructs a {@code DelegatingOAuth2AuthorizedClientProvider} using the provided
* parameters.
* @param authorizedClientProviders a {@code List} of
* {@link OAuth2AuthorizedClientProvider}(s)
*/
public DelegatingOAuth2AuthorizedClientProvider(List<OAuth2AuthorizedClientProvider> authorizedClientProviders) {
Assert.notEmpty(authorizedClientProviders, "authorizedClientProviders cannot be empty");
this.authorizedClientProviders = Collections.unmodifiableList(new ArrayList<>(authorizedClientProviders));
}
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
for (OAuth2AuthorizedClientProvider authorizedClientProvider : this.authorizedClientProviders) {
OAuth2AuthorizedClient oauth2AuthorizedClient = authorizedClientProvider.authorize(context);
if (oauth2AuthorizedClient != null) {
return oauth2AuthorizedClient;
}
}
return null;
}
}
| 3,123 | 38.05 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProvider.java | /*
* Copyright 2002-2022 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.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.endpoint.DefaultPasswordTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
* {@link AuthorizationGrantType#PASSWORD password} grant.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
* @see DefaultPasswordTokenResponseClient
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use of
* the Resource Owner Password Credentials grant. See reference <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public final class PasswordOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
private OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient = new DefaultPasswordTokenResponseClient();
private Duration clockSkew = Duration.ofSeconds(60);
private Clock clock = Clock.systemUTC();
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns {@code null} if authorization (or re-authorization) is not
* supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
* authorization grant type} is not {@link AuthorizationGrantType#PASSWORD password}
* OR the {@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME username} and/or
* {@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME password} attributes are
* not available in the provided {@code context} OR the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
*
* <p>
* The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
* are supported:
* <ol>
* <li>{@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME} (required) - a
* {@code String} value for the resource owner's username</li>
* <li>{@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME} (required) - a
* {@code String} value for the resource owner's password</li>
* </ol>
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization (or
* re-authorization) is not supported
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (!AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType())) {
return null;
}
String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
return null;
}
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// If client is already authorized and access token is NOT expired than no
// need for re-authorization
return null;
}
if (authorizedClient != null && hasTokenExpired(authorizedClient.getAccessToken())
&& authorizedClient.getRefreshToken() != null) {
// If client is already authorized and access token is expired and a refresh
// token is available, than return and allow
// RefreshTokenOAuth2AuthorizedClientProvider to handle the refresh
return null;
}
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username,
password);
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, passwordGrantRequest);
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
}
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
OAuth2PasswordGrantRequest passwordGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(passwordGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code password} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code password} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 7,490 | 43.589286 | 138 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java | /*
* Copyright 2002-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.oauth2.client;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.util.Assert;
/**
* A builder that builds a {@link DelegatingOAuth2AuthorizedClientProvider} composed of
* one or more {@link OAuth2AuthorizedClientProvider}(s) that implement specific
* authorization grants. The supported authorization grants are
* {@link #authorizationCode() authorization_code}, {@link #refreshToken() refresh_token},
* {@link #clientCredentials() client_credentials} and {@link #password() password}. In
* addition to the standard authorization grants, an implementation of an extension grant
* may be supplied via {@link #provider(OAuth2AuthorizedClientProvider)}.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientProvider
* @see AuthorizationCodeOAuth2AuthorizedClientProvider
* @see RefreshTokenOAuth2AuthorizedClientProvider
* @see ClientCredentialsOAuth2AuthorizedClientProvider
* @see PasswordOAuth2AuthorizedClientProvider
* @see DelegatingOAuth2AuthorizedClientProvider
*/
public final class OAuth2AuthorizedClientProviderBuilder {
private final Map<Class<?>, Builder> builders = new LinkedHashMap<>();
private OAuth2AuthorizedClientProviderBuilder() {
}
/**
* Returns a new {@link OAuth2AuthorizedClientProviderBuilder} for configuring the
* supported authorization grant(s).
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public static OAuth2AuthorizedClientProviderBuilder builder() {
return new OAuth2AuthorizedClientProviderBuilder();
}
/**
* Configures an {@link OAuth2AuthorizedClientProvider} to be composed with the
* {@link DelegatingOAuth2AuthorizedClientProvider}. This may be used for
* implementations of extension authorization grants.
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder provider(OAuth2AuthorizedClientProvider provider) {
Assert.notNull(provider, "provider cannot be null");
this.builders.computeIfAbsent(provider.getClass(), (k) -> () -> provider);
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code authorization_code} grant.
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder authorizationCode() {
this.builders.computeIfAbsent(AuthorizationCodeOAuth2AuthorizedClientProvider.class,
(k) -> new AuthorizationCodeGrantBuilder());
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder refreshToken() {
this.builders.computeIfAbsent(RefreshTokenOAuth2AuthorizedClientProvider.class,
(k) -> new RefreshTokenGrantBuilder());
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @param builderConsumer a {@code Consumer} of {@link RefreshTokenGrantBuilder} used
* for further configuration
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder refreshToken(Consumer<RefreshTokenGrantBuilder> builderConsumer) {
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders.computeIfAbsent(
RefreshTokenOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
builderConsumer.accept(builder);
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder clientCredentials() {
this.builders.computeIfAbsent(ClientCredentialsOAuth2AuthorizedClientProvider.class,
(k) -> new ClientCredentialsGrantBuilder());
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @param builderConsumer a {@code Consumer} of {@link ClientCredentialsGrantBuilder}
* used for further configuration
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
*/
public OAuth2AuthorizedClientProviderBuilder clientCredentials(
Consumer<ClientCredentialsGrantBuilder> builderConsumer) {
ClientCredentialsGrantBuilder builder = (ClientCredentialsGrantBuilder) this.builders.computeIfAbsent(
ClientCredentialsOAuth2AuthorizedClientProvider.class, (k) -> new ClientCredentialsGrantBuilder());
builderConsumer.accept(builder);
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code password} grant.
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use
* of the Resource Owner Password Credentials grant. See reference
* <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public OAuth2AuthorizedClientProviderBuilder password() {
this.builders.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code password} grant.
* @param builderConsumer a {@code Consumer} of {@link PasswordGrantBuilder} used for
* further configuration
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use
* of the Resource Owner Password Credentials grant. See reference
* <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public OAuth2AuthorizedClientProviderBuilder password(Consumer<PasswordGrantBuilder> builderConsumer) {
PasswordGrantBuilder builder = (PasswordGrantBuilder) this.builders
.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
builderConsumer.accept(builder);
return OAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Builds an instance of {@link DelegatingOAuth2AuthorizedClientProvider} composed of
* one or more {@link OAuth2AuthorizedClientProvider}(s).
* @return the {@link DelegatingOAuth2AuthorizedClientProvider}
*/
public OAuth2AuthorizedClientProvider build() {
List<OAuth2AuthorizedClientProvider> authorizedClientProviders = new ArrayList<>();
for (Builder builder : this.builders.values()) {
authorizedClientProviders.add(builder.build());
}
return new DelegatingOAuth2AuthorizedClientProvider(authorizedClientProviders);
}
interface Builder {
OAuth2AuthorizedClientProvider build();
}
/**
* A builder for the {@code password} grant.
*/
public final class PasswordGrantBuilder implements Builder {
private OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private PasswordGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link PasswordGrantBuilder}
*/
public PasswordGrantBuilder accessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link PasswordGrantBuilder}
* @see PasswordOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public PasswordGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link PasswordGrantBuilder}
*/
public PasswordGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of {@link PasswordOAuth2AuthorizedClientProvider}.
* @return the {@link PasswordOAuth2AuthorizedClientProvider}
*/
@Override
public OAuth2AuthorizedClientProvider build() {
PasswordOAuth2AuthorizedClientProvider authorizedClientProvider = new PasswordOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
/**
* A builder for the {@code client_credentials} grant.
*/
public final class ClientCredentialsGrantBuilder implements Builder {
private OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private ClientCredentialsGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link ClientCredentialsGrantBuilder}
*/
public ClientCredentialsGrantBuilder accessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link ClientCredentialsGrantBuilder}
* @see ClientCredentialsOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public ClientCredentialsGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link ClientCredentialsGrantBuilder}
*/
public ClientCredentialsGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of {@link ClientCredentialsOAuth2AuthorizedClientProvider}.
* @return the {@link ClientCredentialsOAuth2AuthorizedClientProvider}
*/
@Override
public OAuth2AuthorizedClientProvider build() {
ClientCredentialsOAuth2AuthorizedClientProvider authorizedClientProvider = new ClientCredentialsOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
/**
* A builder for the {@code authorization_code} grant.
*/
public final class AuthorizationCodeGrantBuilder implements Builder {
private AuthorizationCodeGrantBuilder() {
}
/**
* Builds an instance of {@link AuthorizationCodeOAuth2AuthorizedClientProvider}.
* @return the {@link AuthorizationCodeOAuth2AuthorizedClientProvider}
*/
@Override
public OAuth2AuthorizedClientProvider build() {
return new AuthorizationCodeOAuth2AuthorizedClientProvider();
}
}
/**
* A builder for the {@code refresh_token} grant.
*/
public final class RefreshTokenGrantBuilder implements Builder {
private OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient;
private Duration clockSkew;
private Clock clock;
private RefreshTokenGrantBuilder() {
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint.
* @param accessTokenResponseClient the client used when requesting an access
* token credential at the Token Endpoint
* @return the {@link RefreshTokenGrantBuilder}
*/
public RefreshTokenGrantBuilder accessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link RefreshTokenGrantBuilder}
* @see RefreshTokenOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link RefreshTokenGrantBuilder}
*/
public RefreshTokenGrantBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Builds an instance of {@link RefreshTokenOAuth2AuthorizedClientProvider}.
* @return the {@link RefreshTokenOAuth2AuthorizedClientProvider}
*/
@Override
public OAuth2AuthorizedClientProvider build() {
RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
}
| 15,865 | 35.983683 | 132 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientOAuth2AuthorizationFailureHandler.java | /*
* Copyright 2002-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.client;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.Assert;
/**
* An {@link OAuth2AuthorizationFailureHandler} that removes an
* {@link OAuth2AuthorizedClient} when the {@link OAuth2Error#getErrorCode()} matches one
* of the configured {@link OAuth2ErrorCodes OAuth 2.0 error codes}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientRepository
* @see OAuth2AuthorizedClientService
*/
public class RemoveAuthorizedClientOAuth2AuthorizationFailureHandler implements OAuth2AuthorizationFailureHandler {
/**
* The default OAuth 2.0 error codes that will trigger removal of an
* {@link OAuth2AuthorizedClient}.
* @see OAuth2ErrorCodes
*/
public static final Set<String> DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES;
static {
Set<String> codes = new LinkedHashSet<>();
// Returned from Resource Servers when an access token provided is expired,
// revoked, malformed, or invalid for other reasons. Note that this is needed
// because ServletOAuth2AuthorizedClientExchangeFilterFunction delegates this type
// of failure received from a Resource Server to this failure handler.
codes.add(OAuth2ErrorCodes.INVALID_TOKEN);
// Returned from Authorization Servers when the authorization grant or refresh
// token is invalid, expired, revoked, does not match the redirection URI used in
// the authorization request, or was issued to another client.
codes.add(OAuth2ErrorCodes.INVALID_GRANT);
DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES = Collections.unmodifiableSet(codes);
}
/**
* The OAuth 2.0 error codes which will trigger removal of an
* {@link OAuth2AuthorizedClient}.
* @see OAuth2ErrorCodes
*/
private final Set<String> removeAuthorizedClientErrorCodes;
/**
* A delegate that removes an {@link OAuth2AuthorizedClient} from an
* {@link OAuth2AuthorizedClientRepository} or {@link OAuth2AuthorizedClientService}
* if the error code is one of the {@link #removeAuthorizedClientErrorCodes}.
*/
private final OAuth2AuthorizedClientRemover delegate;
/**
* Constructs a {@code RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} using
* the provided parameters.
* @param authorizedClientRemover the {@link OAuth2AuthorizedClientRemover} used for
* removing an {@link OAuth2AuthorizedClient} if the error code is one of the
* {@link #DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES}.
*/
public RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
OAuth2AuthorizedClientRemover authorizedClientRemover) {
this(authorizedClientRemover, DEFAULT_REMOVE_AUTHORIZED_CLIENT_ERROR_CODES);
}
/**
* Constructs a {@code RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} using
* the provided parameters.
* @param authorizedClientRemover the {@link OAuth2AuthorizedClientRemover} used for
* removing an {@link OAuth2AuthorizedClient} if the error code is one of the
* {@link #removeAuthorizedClientErrorCodes}.
* @param removeAuthorizedClientErrorCodes the OAuth 2.0 error codes which will
* trigger removal of an authorized client.
* @see OAuth2ErrorCodes
*/
public RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
OAuth2AuthorizedClientRemover authorizedClientRemover, Set<String> removeAuthorizedClientErrorCodes) {
Assert.notNull(authorizedClientRemover, "authorizedClientRemover cannot be null");
Assert.notNull(removeAuthorizedClientErrorCodes, "removeAuthorizedClientErrorCodes cannot be null");
this.removeAuthorizedClientErrorCodes = Collections
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
this.delegate = authorizedClientRemover;
}
@Override
public void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal,
Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) {
this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(), principal,
attributes);
}
}
/**
* Returns true if the given exception has an error code that indicates that the
* authorized client should be removed.
* @param authorizationException the exception that caused the authorization failure
* @return true if the given exception has an error code that indicates that the
* authorized client should be removed.
*/
private boolean hasRemovalErrorCode(OAuth2AuthorizationException authorizationException) {
return this.removeAuthorizedClientErrorCodes.contains(authorizationException.getError().getErrorCode());
}
/**
* Removes an {@link OAuth2AuthorizedClient} from an
* {@link OAuth2AuthorizedClientRepository} or {@link OAuth2AuthorizedClientService}.
*/
@FunctionalInterface
public interface OAuth2AuthorizedClientRemover {
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner).
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param attributes an immutable {@code Map} of (optional) attributes present
* under certain conditions. For example, this might contain a
* {@code jakarta.servlet.http.HttpServletRequest} and
* {@code jakarta.servlet.http.HttpServletResponse} if the authorization was
* performed within the context of a {@code jakarta.servlet.ServletContext}.
*/
void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
Map<String, Object> attributes);
}
}
| 6,813 | 42.96129 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverter.java | /*
* Copyright 2002-2018 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.client.userinfo;
import java.net.URI;
import java.util.Collections;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A {@link Converter} that converts the provided {@link OAuth2UserRequest} to a
* {@link RequestEntity} representation of a request for the UserInfo Endpoint.
*
* @author Joe Grandja
* @since 5.1
* @see Converter
* @see OAuth2UserRequest
* @see RequestEntity
*/
public class OAuth2UserRequestEntityConverter implements Converter<OAuth2UserRequest, RequestEntity<?>> {
private static final MediaType DEFAULT_CONTENT_TYPE = MediaType
.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
/**
* Returns the {@link RequestEntity} used for the UserInfo Request.
* @param userRequest the user request
* @return the {@link RequestEntity} used for the UserInfo Request
*/
@Override
public RequestEntity<?> convert(OAuth2UserRequest userRequest) {
ClientRegistration clientRegistration = userRequest.getClientRegistration();
HttpMethod httpMethod = getHttpMethod(clientRegistration);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
URI uri = UriComponentsBuilder
.fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()).build().toUri();
RequestEntity<?> request;
if (HttpMethod.POST.equals(httpMethod)) {
headers.setContentType(DEFAULT_CONTENT_TYPE);
MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
formParameters.add(OAuth2ParameterNames.ACCESS_TOKEN, userRequest.getAccessToken().getTokenValue());
request = new RequestEntity<>(formParameters, headers, httpMethod, uri);
}
else {
headers.setBearerAuth(userRequest.getAccessToken().getTokenValue());
request = new RequestEntity<>(headers, httpMethod, uri);
}
return request;
}
private HttpMethod getHttpMethod(ClientRegistration clientRegistration) {
if (AuthenticationMethod.FORM
.equals(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())) {
return HttpMethod.POST;
}
return HttpMethod.GET;
}
}
| 3,383 | 37.896552 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserService.java | /*
* Copyright 2002-2017 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.client.userinfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2UserService} that simply delegates to it's
* internal {@code List} of {@link OAuth2UserService}(s).
* <p>
* Each {@link OAuth2UserService} is given a chance to
* {@link OAuth2UserService#loadUser(OAuth2UserRequest) load} an {@link OAuth2User} with
* the first {@code non-null} {@link OAuth2User} being returned.
*
* @param <R> The type of OAuth 2.0 User Request
* @param <U> The type of OAuth 2.0 User
* @author Joe Grandja
* @since 5.0
* @see OAuth2UserService
* @see OAuth2UserRequest
* @see OAuth2User
*/
public class DelegatingOAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User>
implements OAuth2UserService<R, U> {
private final List<OAuth2UserService<R, U>> userServices;
/**
* Constructs a {@code DelegatingOAuth2UserService} using the provided parameters.
* @param userServices a {@code List} of {@link OAuth2UserService}(s)
*/
public DelegatingOAuth2UserService(List<OAuth2UserService<R, U>> userServices) {
Assert.notEmpty(userServices, "userServices cannot be empty");
this.userServices = Collections.unmodifiableList(new ArrayList<>(userServices));
}
@Override
public U loadUser(R userRequest) throws OAuth2AuthenticationException {
Assert.notNull(userRequest, "userRequest cannot be null");
// @formatter:off
return this.userServices.stream()
.map((userService) -> userService.loadUser(userRequest))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
// @formatter:on
}
}
| 2,488 | 34.056338 | 91 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/package-info.java | /*
* Copyright 2002-2017 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.
*/
/**
* Classes and interfaces providing support to the client for initiating requests to the
* OAuth 2.0 Authorization Server's UserInfo Endpoint.
*/
package org.springframework.security.oauth2.client.userinfo;
| 836 | 37.045455 | 88 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/ReactiveOAuth2UserService.java | /*
* Copyright 2002-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.client.userinfo;
import reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
/**
* Implementations of this interface are responsible for obtaining the user attributes of
* the End-User (Resource Owner) from the UserInfo Endpoint using the
* {@link OAuth2UserRequest#getAccessToken() Access Token} granted to the
* {@link OAuth2UserRequest#getClientRegistration() Client} and returning an
* {@link AuthenticatedPrincipal} in the form of an {@link OAuth2User}.
*
* @param <R> The type of OAuth 2.0 User Request
* @param <U> The type of OAuth 2.0 User
* @author Rob Winch
* @since 5.1
* @see OAuth2UserRequest
* @see OAuth2User
* @see AuthenticatedPrincipal
*/
@FunctionalInterface
public interface ReactiveOAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User> {
/**
* Returns an {@link OAuth2User} after obtaining the user attributes of the End-User
* from the UserInfo Endpoint.
* @param userRequest the user request
* @return an {@link OAuth2User}
* @throws OAuth2AuthenticationException if an error occurs while attempting to obtain
* the user attributes from the UserInfo Endpoint
*/
Mono<U> loadUser(R userRequest) throws OAuth2AuthenticationException;
}
| 2,060 | 37.166667 | 95 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequest.java | /*
* Copyright 2002-2018 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.client.userinfo;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Represents a request the {@link OAuth2UserService} uses when initiating a request to
* the UserInfo Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see ClientRegistration
* @see OAuth2AccessToken
* @see OAuth2UserService
*/
public class OAuth2UserRequest {
private final ClientRegistration clientRegistration;
private final OAuth2AccessToken accessToken;
private final Map<String, Object> additionalParameters;
/**
* Constructs an {@code OAuth2UserRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param accessToken the access token
*/
public OAuth2UserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken) {
this(clientRegistration, accessToken, Collections.emptyMap());
}
/**
* Constructs an {@code OAuth2UserRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param accessToken the access token
* @param additionalParameters the additional parameters, may be empty
* @since 5.1
*/
public OAuth2UserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken,
Map<String, Object> additionalParameters) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
Assert.notNull(accessToken, "accessToken cannot be null");
this.clientRegistration = clientRegistration;
this.accessToken = accessToken;
this.additionalParameters = Collections.unmodifiableMap(CollectionUtils.isEmpty(additionalParameters)
? Collections.emptyMap() : new LinkedHashMap<>(additionalParameters));
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the additional parameters that may be used in the request.
* @return a {@code Map} of the additional parameters, may be empty.
* @since 5.1
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
}
| 3,257 | 32.244898 | 103 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserService.java | /*
* Copyright 2002-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.client.userinfo;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.UnknownContentTypeException;
/**
* An implementation of an {@link OAuth2UserService} that supports standard OAuth 2.0
* Provider's.
* <p>
* For standard OAuth 2.0 Provider's, the attribute name used to access the user's name
* from the UserInfo response is required and therefore must be available via
* {@link ClientRegistration.ProviderDetails.UserInfoEndpoint#getUserNameAttributeName()
* UserInfoEndpoint.getUserNameAttributeName()}.
* <p>
* <b>NOTE:</b> Attribute names are <b>not</b> standardized between providers and
* therefore will vary. Please consult the provider's API documentation for the set of
* supported user attribute names.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2UserService
* @see OAuth2UserRequest
* @see OAuth2User
* @see DefaultOAuth2User
*/
public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri";
private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute";
private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
private static final ParameterizedTypeReference<Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE = new ParameterizedTypeReference<Map<String, Object>>() {
};
private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();
private RestOperations restOperations;
public DefaultOAuth2UserService() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
Assert.notNull(userRequest, "userRequest cannot be null");
if (!StringUtils
.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
"Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
.getUserNameAttributeName();
if (!StringUtils.hasText(userNameAttributeName)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
"Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request);
Map<String, Object> userAttributes = response.getBody();
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OAuth2UserAuthority(userAttributes));
OAuth2AccessToken token = userRequest.getAccessToken();
for (String authority : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
}
private ResponseEntity<Map<String, Object>> getResponse(OAuth2UserRequest userRequest, RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
}
catch (OAuth2AuthorizationException ex) {
OAuth2Error oauth2Error = ex.getError();
StringBuilder errorDetails = new StringBuilder();
errorDetails.append("Error details: [");
errorDetails.append("UserInfo Uri: ")
.append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode());
if (oauth2Error.getDescription() != null) {
errorDetails.append(", Error Description: ").append(oauth2Error.getDescription());
}
errorDetails.append("]");
oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the UserInfo Resource: " + errorDetails.toString(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}
catch (UnknownContentTypeException ex) {
String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '"
+ userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri()
+ "': response contains invalid content type '" + ex.getContentType().toString() + "'. "
+ "The UserInfo Response should return a JSON object (content type 'application/json') "
+ "that contains a collection of name and value pairs of the claims about the authenticated End-User. "
+ "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '"
+ userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, "
+ "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the UserInfo Resource: " + ex.getMessage(), null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}
}
/**
* Sets the {@link Converter} used for converting the {@link OAuth2UserRequest} to a
* {@link RequestEntity} representation of the UserInfo Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the UserInfo Request
* @since 5.1
*/
public final void setRequestEntityConverter(Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the UserInfo resource.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the UserInfo
* resource
* @since 5.1
*/
public final void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 9,219 | 47.783069 | 155 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.