Search in sources :

Example 41 with OAuth2AccessTokenResponse

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

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// 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());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Mock(org.mockito.Mock) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JwtException(org.springframework.security.oauth2.jwt.JwtException) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) Test(org.junit.jupiter.api.Test)

Example 42 with OAuth2AccessTokenResponse

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

the class DefaultJwtBearerTokenResponseClientTests 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();
    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();
}
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)

Example 43 with OAuth2AccessTokenResponse

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

the class DefaultJwtBearerTokenResponseClientTests method getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasDefaultScope.

@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasDefaultScope() {
    // @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()).containsExactly("read", "write");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Test(org.junit.jupiter.api.Test)

Example 44 with OAuth2AccessTokenResponse

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

the class DefaultJwtBearerTokenResponseClientTests method getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope.

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

Example 45 with OAuth2AccessTokenResponse

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

the class RefreshTokenOAuth2AuthorizedClientProviderTests method authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize.

@Test
public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("new-refresh-token").build();
    // @formatter:on
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(this.authorizedClient).principal(this.principal).build();
    // @formatter:on
    OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
    assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) 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