Search in sources :

Example 96 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class RefreshTokenOAuth2AuthorizedClientProviderTests method authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested.

@Test
public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("new-refresh-token").build();
    // @formatter:on
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    String[] requestScope = new String[] { "read", "write" };
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(this.authorizedClient).principal(this.principal).attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, requestScope).build();
    // @formatter:on
    this.authorizedClientProvider.authorize(authorizationContext);
    ArgumentCaptor<OAuth2RefreshTokenGrantRequest> refreshTokenGrantRequestArgCaptor = ArgumentCaptor.forClass(OAuth2RefreshTokenGrantRequest.class);
    verify(this.accessTokenResponseClient).getTokenResponse(refreshTokenGrantRequestArgCaptor.capture());
    assertThat(refreshTokenGrantRequestArgCaptor.getValue().getScopes()).isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) Test(org.junit.jupiter.api.Test)

Example 97 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationProviderTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// 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());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashSet(java.util.LinkedHashSet) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Set(java.util.Set) Instant(java.time.Instant) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) List(java.util.List) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2UserService(org.springframework.security.oauth2.client.userinfo.OAuth2UserService) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Test(org.junit.jupiter.api.Test)

Example 98 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenSpecialCharactersThenSuccessWithEncodedClientCredentials.

// 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();
    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");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.jupiter.api.Test)

Example 99 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenNoScopeThenClientRegistrationScopesDefaulted.

@Test
public void getTokenResponseWhenNoScopeThenClientRegistrationScopesDefaulted() {
    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()).isEqualTo(registration.getScopes());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 100 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class DefaultPasswordTokenResponseClientTests method getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse.

@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);
    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();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)134 Test (org.junit.jupiter.api.Test)122 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)43 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)40 Instant (java.time.Instant)37 HashMap (java.util.HashMap)32 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)27 Mono (reactor.core.publisher.Mono)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)15 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)15 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11