Search in sources :

Example 21 with OAuth2AuthorizeRequest

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

the class DefaultOAuth2AuthorizedClientManagerTests method authorizeWhenHttpServletResponseIsNullThenThrowIllegalArgumentException.

@Test
public void authorizeWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() {
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).attribute(HttpServletRequest.class.getName(), this.request).build();
    assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)).withMessage("servletResponse cannot be null");
}
Also used : OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) Test(org.junit.jupiter.api.Test)

Example 22 with OAuth2AuthorizeRequest

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

the class DefaultOAuth2AuthorizedClientManagerTests method reauthorizeWhenUnsupportedProviderThenNotReauthorized.

@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
    // @formatter:off
    OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient).principal(this.principal).attributes((attrs) -> {
        attrs.put(HttpServletRequest.class.getName(), this.request);
        attrs.put(HttpServletResponse.class.getName(), this.response);
    }).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    assertThat(authorizedClient).isSameAs(this.authorizedClient);
    verifyNoInteractions(this.authorizationSuccessHandler);
    verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class), eq(this.principal), eq(this.request), eq(this.response));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) 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) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 23 with OAuth2AuthorizeRequest

use of org.springframework.security.oauth2.client.OAuth2AuthorizeRequest 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 24 with OAuth2AuthorizeRequest

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

the class DefaultReactiveOAuth2AuthorizedClientManager method authorize.

@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
    Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
    String clientRegistrationId = authorizeRequest.getClientRegistrationId();
    Authentication principal = authorizeRequest.getPrincipal();
    // @formatter:off
    return Mono.justOrEmpty(authorizeRequest.<ServerWebExchange>getAttribute(ServerWebExchange.class.getName())).switchIfEmpty(currentServerWebExchangeMono).switchIfEmpty(Mono.error(() -> new IllegalArgumentException("serverWebExchange cannot be null"))).flatMap((serverWebExchange) -> Mono.justOrEmpty(authorizeRequest.getAuthorizedClient()).switchIfEmpty(Mono.defer(() -> loadAuthorizedClient(clientRegistrationId, principal, serverWebExchange))).flatMap((// Re-authorize
    authorizedClient) -> authorizationContext(authorizeRequest, authorizedClient).flatMap((authorizationContext) -> authorize(authorizationContext, principal, serverWebExchange)).defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null) ? authorizeRequest.getAuthorizedClient() : authorizedClient)).switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId).switchIfEmpty(Mono.error(() -> new IllegalArgumentException("Could not find ClientRegistration with id '" + clientRegistrationId + "'"))).flatMap((clientRegistration) -> authorizationContext(authorizeRequest, clientRegistration)).flatMap((authorizationContext) -> authorize(authorizationContext, principal, serverWebExchange)))));
// @formatter:on
}
Also used : OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) ReactiveOAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder) ReactiveOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) HashMap(java.util.HashMap) Mono(reactor.core.publisher.Mono) Function(java.util.function.Function) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager) ReactiveOAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationSuccessHandler) CollectionUtils(org.springframework.util.CollectionUtils) Map(java.util.Map) ReactiveOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler) RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Authentication(org.springframework.security.core.Authentication)

Example 25 with OAuth2AuthorizeRequest

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunction method reauthorizeClient.

private Mono<OAuth2AuthorizedClient> reauthorizeClient(OAuth2AuthorizedClient authorizedClient, ClientRequest request) {
    if (this.authorizedClientManager == null) {
        return Mono.just(authorizedClient);
    }
    Map<String, Object> attrs = request.attributes();
    Authentication authentication = getAuthentication(attrs);
    if (authentication == null) {
        authentication = createAuthentication(authorizedClient.getPrincipalName());
    }
    HttpServletRequest servletRequest = getRequest(attrs);
    HttpServletResponse servletResponse = getResponse(attrs);
    OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient).principal(authentication);
    builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
    OAuth2AuthorizeRequest reauthorizeRequest = builder.build();
    // blocking I/O operation using RestTemplate internally
    return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(reauthorizeRequest)).subscribeOn(Schedulers.boundedElastic());
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)

Aggregations

Test (org.junit.jupiter.api.Test)34 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)32 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)25 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)23 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)20 Authentication (org.springframework.security.core.Authentication)18 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)14 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)14 Map (java.util.Map)14 Function (java.util.function.Function)14 ClientAuthorizationException (org.springframework.security.oauth2.client.ClientAuthorizationException)14 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)14 HashMap (java.util.HashMap)13 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)13 OAuth2ErrorCodes (org.springframework.security.oauth2.core.OAuth2ErrorCodes)12 StringUtils (org.springframework.util.StringUtils)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 BeforeEach (org.junit.jupiter.api.BeforeEach)11