Search in sources :

Example 56 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext in project spring-security by spring-projects.

the class DefaultOAuth2AuthorizedClientManager method authorize.

@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();
    HttpServletRequest servletRequest = getHttpServletRequestOrDefault(authorizeRequest.getAttributes());
    Assert.notNull(servletRequest, "servletRequest cannot be null");
    HttpServletResponse servletResponse = getHttpServletResponseOrDefault(authorizeRequest.getAttributes());
    Assert.notNull(servletResponse, "servletResponse cannot be null");
    OAuth2AuthorizationContext.Builder contextBuilder;
    if (authorizedClient != null) {
        contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
    } else {
        authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, servletRequest);
        if (authorizedClient != null) {
            contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
        } else {
            ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
            Assert.notNull(clientRegistration, "Could not find ClientRegistration with id '" + clientRegistrationId + "'");
            contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
        }
    }
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal).attributes((attributes) -> {
        Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
        if (!CollectionUtils.isEmpty(contextAttributes)) {
            attributes.putAll(contextAttributes);
        }
    }).build();
    // @formatter:on
    try {
        authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    } catch (OAuth2AuthorizationException ex) {
        this.authorizationFailureHandler.onAuthorizationFailure(ex, principal, createAttributes(servletRequest, servletResponse));
        throw ex;
    }
    if (authorizedClient != null) {
        this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal, createAttributes(servletRequest, servletResponse));
    } else {
        // `authorizationContext.authorizedClient`.
        if (authorizationContext.getAuthorizedClient() != null) {
            return authorizationContext.getAuthorizedClient();
        }
    }
    return authorizedClient;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) AuthorizedClientServiceOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager) Function(java.util.function.Function) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) Map(java.util.Map) OAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager) RequestAttributes(org.springframework.web.context.request.RequestAttributes) Nullable(org.springframework.lang.Nullable) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) CollectionUtils(org.springframework.util.CollectionUtils) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashMap(java.util.HashMap) Map(java.util.Map) Nullable(org.springframework.lang.Nullable)

Example 57 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext in project spring-security by spring-projects.

the class JwtBearerReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize.

@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Test(org.junit.jupiter.api.Test)

Example 58 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext in project spring-security by spring-projects.

the class JwtBearerReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenCustomJwtAssertionResolverSetThenUsed.

@Test
public void authorizeWhenCustomJwtAssertionResolverSetThenUsed() {
    Function<OAuth2AuthorizationContext, Mono<Jwt>> jwtAssertionResolver = mock(Function.class);
    given(jwtAssertionResolver.apply(any())).willReturn(Mono.just(this.jwtAssertion));
    this.authorizedClientProvider.setJwtAssertionResolver(jwtAssertionResolver);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    verify(jwtAssertionResolver).apply(any());
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Mono(reactor.core.publisher.Mono) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 59 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext in project spring-security by spring-projects.

the class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests method authorizeWhenInvalidGrantThenRemoveAuthorizedClient.

@Test
public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(Mono.just(this.clientRegistration));
    given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).build();
    // @formatter:on
    ClientAuthorizationException exception = new ClientAuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null), this.clientRegistration.getRegistrationId());
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.error(exception));
    assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isNull();
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), eq(this.principal.getName()));
    this.removeAuthorizedClientProbe.assertWasSubscribed();
    verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Example 60 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext in project spring-security by spring-projects.

the class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenNotClientCredentialsThenUnableToAuthorize.

@Test
public void authorizeWhenNotClientCredentialsThenUnableToAuthorize() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(this.principal).build();
    // @formatter:on
    assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)67 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)31 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)30 Instant (java.time.Instant)21 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)21 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)21 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)19 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)17 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)15 Authentication (org.springframework.security.core.Authentication)14 Function (java.util.function.Function)11 ClientAuthorizationException (org.springframework.security.oauth2.client.ClientAuthorizationException)11 Map (java.util.Map)10 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)10 HashMap (java.util.HashMap)9 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)9 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)9 BeforeEach (org.junit.jupiter.api.BeforeEach)9