Search in sources :

Example 6 with AuthorizationRequestRepository

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

the class ServerHttpSecurityTests method shouldConfigureAuthorizationRequestRepositoryForOAuth2Login.

@Test
public void shouldConfigureAuthorizationRequestRepositoryForOAuth2Login() {
    ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(ServerAuthorizationRequestRepository.class);
    ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
    given(authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(authorizationRequest));
    SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).authorizationRequestRepository(authorizationRequestRepository).and().build();
    WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
    client.get().uri("/login/oauth2/code/registration-id").exchange();
    verify(authorizationRequestRepository).removeAuthorizationRequest(any());
}
Also used : ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) Test(org.junit.jupiter.api.Test)

Example 7 with AuthorizationRequestRepository

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

the class OAuth2LoginBeanDefinitionParser method parse.

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // register magic bean
    BeanDefinition oauth2LoginBeanConfig = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginBeanConfig.class).getBeanDefinition();
    String oauth2LoginBeanConfigId = parserContext.getReaderContext().generateBeanName(oauth2LoginBeanConfig);
    parserContext.registerBeanComponent(new BeanComponentDefinition(oauth2LoginBeanConfig, oauth2LoginBeanConfigId));
    // configure filter
    BeanMetadataElement clientRegistrationRepository = OAuth2ClientBeanDefinitionParserUtils.getClientRegistrationRepository(element);
    BeanMetadataElement authorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientRepository(element);
    if (authorizedClientRepository == null) {
        BeanMetadataElement authorizedClientService = OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientService(element);
        this.defaultAuthorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils.createDefaultAuthorizedClientRepository(clientRegistrationRepository, authorizedClientService);
        authorizedClientRepository = new RuntimeBeanReference(OAuth2AuthorizedClientRepository.class);
    }
    BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(element);
    BeanMetadataElement oauth2UserService = getOAuth2UserService(element);
    BeanMetadataElement authorizationRequestRepository = getAuthorizationRequestRepository(element);
    BeanDefinitionBuilder oauth2LoginAuthenticationFilterBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginAuthenticationFilter.class).addConstructorArgValue(clientRegistrationRepository).addConstructorArgValue(authorizedClientRepository).addPropertyValue("authorizationRequestRepository", authorizationRequestRepository);
    if (this.sessionStrategy != null) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("sessionAuthenticationStrategy", this.sessionStrategy);
    }
    Object source = parserContext.extractSource(element);
    String loginProcessingUrl = element.getAttribute(ATT_LOGIN_PROCESSING_URL);
    if (!StringUtils.isEmpty(loginProcessingUrl)) {
        WebConfigUtils.validateHttpRedirect(loginProcessingUrl, parserContext, source);
        oauth2LoginAuthenticationFilterBuilder.addConstructorArgValue(loginProcessingUrl);
    } else {
        oauth2LoginAuthenticationFilterBuilder.addConstructorArgValue(OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI);
    }
    BeanDefinitionBuilder oauth2LoginAuthenticationProviderBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2LoginAuthenticationProvider.class).addConstructorArgValue(accessTokenResponseClient).addConstructorArgValue(oauth2UserService);
    String userAuthoritiesMapperRef = element.getAttribute(ATT_USER_AUTHORITIES_MAPPER_REF);
    if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) {
        oauth2LoginAuthenticationProviderBuilder.addPropertyReference("authoritiesMapper", userAuthoritiesMapperRef);
    }
    this.oauth2LoginAuthenticationProvider = oauth2LoginAuthenticationProviderBuilder.getBeanDefinition();
    this.oauth2LoginOidcAuthenticationProvider = getOidcAuthProvider(element, accessTokenResponseClient, userAuthoritiesMapperRef);
    BeanDefinitionBuilder oauth2AuthorizationRequestRedirectFilterBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2AuthorizationRequestRedirectFilter.class);
    String authorizationRequestResolverRef = element.getAttribute(ATT_AUTHORIZATION_REQUEST_RESOLVER_REF);
    if (!StringUtils.isEmpty(authorizationRequestResolverRef)) {
        oauth2AuthorizationRequestRedirectFilterBuilder.addConstructorArgReference(authorizationRequestResolverRef);
    } else {
        oauth2AuthorizationRequestRedirectFilterBuilder.addConstructorArgValue(clientRegistrationRepository);
    }
    oauth2AuthorizationRequestRedirectFilterBuilder.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository).addPropertyValue("requestCache", this.requestCache);
    this.oauth2AuthorizationRequestRedirectFilter = oauth2AuthorizationRequestRedirectFilterBuilder.getBeanDefinition();
    String authenticationSuccessHandlerRef = element.getAttribute(ATT_AUTHENTICATION_SUCCESS_HANDLER_REF);
    if (!StringUtils.isEmpty(authenticationSuccessHandlerRef)) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyReference("authenticationSuccessHandler", authenticationSuccessHandlerRef);
    } else {
        BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler").addPropertyValue("requestCache", this.requestCache);
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler", successHandlerBuilder.getBeanDefinition());
    }
    String loginPage = element.getAttribute(ATT_LOGIN_PAGE);
    if (!StringUtils.isEmpty(loginPage)) {
        WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source);
        this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder.rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class).addConstructorArgValue(loginPage).addPropertyValue("portMapper", this.portMapper).addPropertyValue("portResolver", this.portResolver).getBeanDefinition();
    } else {
        Map<RequestMatcher, AuthenticationEntryPoint> entryPoint = getLoginEntryPoint(element);
        if (entryPoint != null) {
            this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder.rootBeanDefinition(DelegatingAuthenticationEntryPoint.class).addConstructorArgValue(entryPoint).addPropertyValue("defaultEntryPoint", new LoginUrlAuthenticationEntryPoint(DEFAULT_LOGIN_URI)).getBeanDefinition();
        }
    }
    String authenticationFailureHandlerRef = element.getAttribute(ATT_AUTHENTICATION_FAILURE_HANDLER_REF);
    if (!StringUtils.isEmpty(authenticationFailureHandlerRef)) {
        oauth2LoginAuthenticationFilterBuilder.addPropertyReference("authenticationFailureHandler", authenticationFailureHandlerRef);
    } else {
        BeanDefinitionBuilder failureHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler");
        failureHandlerBuilder.addConstructorArgValue(DEFAULT_LOGIN_URI + "?" + DefaultLoginPageGeneratingFilter.ERROR_PARAMETER_NAME);
        failureHandlerBuilder.addPropertyValue("allowSessionCreation", this.allowSessionCreation);
        oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationFailureHandler", failureHandlerBuilder.getBeanDefinition());
    }
    // prepare loginlinks
    this.oauth2LoginLinks = BeanDefinitionBuilder.rootBeanDefinition(Map.class).setFactoryMethodOnBean("getLoginLinks", oauth2LoginBeanConfigId).getBeanDefinition();
    return oauth2LoginAuthenticationFilterBuilder.getBeanDefinition();
}
Also used : RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) AndRequestMatcher(org.springframework.security.web.util.matcher.AndRequestMatcher) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) MediaTypeRequestMatcher(org.springframework.security.web.util.matcher.MediaTypeRequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) OAuth2LoginAuthenticationFilter(org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) DelegatingAuthenticationEntryPoint(org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint) BeanComponentDefinition(org.springframework.beans.factory.parsing.BeanComponentDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with AuthorizationRequestRepository

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

the class OAuth2ClientConfigurerTests method configureWhenRequestCacheProvidedAndClientAuthorizationSucceedsThenRequestCacheUsed.

@Test
public void configureWhenRequestCacheProvidedAndClientAuthorizationSucceedsThenRequestCacheUsed() throws Exception {
    this.spring.register(OAuth2ClientConfig.class).autowire();
    // Setup the Authorization Request in the session
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, this.registration1.getRegistrationId());
    // @formatter:off
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().authorizationUri(this.registration1.getProviderDetails().getAuthorizationUri()).clientId(this.registration1.getClientId()).redirectUri("http://localhost/client-1").state("state").attributes(attributes).build();
    // @formatter:on
    AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
    MockHttpServletResponse response = new MockHttpServletResponse();
    authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
    MockHttpSession session = (MockHttpSession) request.getSession();
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    // @formatter:off
    MockHttpServletRequestBuilder clientRequest = get("/client-1").param(OAuth2ParameterNames.CODE, "code").param(OAuth2ParameterNames.STATE, "state").with(authentication(authentication)).session(session);
    this.mockMvc.perform(clientRequest).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/client-1"));
    // @formatter:on
    verify(requestCache).getRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpSessionOAuth2AuthorizationRequestRepository(org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 9 with AuthorizationRequestRepository

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

the class OAuth2ClientConfigurerTests method configureWhenAuthorizationCodeResponseSuccessThenAuthorizedClientSaved.

@Test
public void configureWhenAuthorizationCodeResponseSuccessThenAuthorizedClientSaved() throws Exception {
    this.spring.register(OAuth2ClientConfig.class).autowire();
    // Setup the Authorization Request in the session
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, this.registration1.getRegistrationId());
    // @formatter:off
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().authorizationUri(this.registration1.getProviderDetails().getAuthorizationUri()).clientId(this.registration1.getClientId()).redirectUri("http://localhost/client-1").state("state").attributes(attributes).build();
    // @formatter:on
    AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
    MockHttpServletResponse response = new MockHttpServletResponse();
    authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
    MockHttpSession session = (MockHttpSession) request.getSession();
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    // @formatter:off
    MockHttpServletRequestBuilder clientRequest = get("/client-1").param(OAuth2ParameterNames.CODE, "code").param(OAuth2ParameterNames.STATE, "state").with(authentication(authentication)).session(session);
    this.mockMvc.perform(clientRequest).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/client-1"));
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), authentication, request);
    assertThat(authorizedClient).isNotNull();
}
Also used : HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpSessionOAuth2AuthorizationRequestRepository(org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository) MockHttpSession(org.springframework.mock.web.MockHttpSession) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 10 with AuthorizationRequestRepository

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

the class OAuth2AuthorizationRequestRedirectFilterTests method doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved.

@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved() throws Exception {
    String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration2.getRegistrationId();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setServletPath(requestUri);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(AuthorizationRequestRepository.class);
    this.filter.setAuthorizationRequestRepository(authorizationRequestRepository);
    this.filter.doFilter(request, response, filterChain);
    verifyZeroInteractions(filterChain);
    verify(authorizationRequestRepository).saveAuthorizationRequest(any(OAuth2AuthorizationRequest.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)8 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)4 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)3 HashMap (java.util.HashMap)3 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)3 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)3 ReactiveClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository)3 ServerOAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository)3 SecurityWebFilterChain (org.springframework.security.web.server.SecurityWebFilterChain)3 WebTestClient (org.springframework.test.web.reactive.server.WebTestClient)3 URI (java.net.URI)2 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)2 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)2 BDDMockito.given (org.mockito.BDDMockito.given)2 Mockito.mock (org.mockito.Mockito.mock)2 Mockito.verify (org.mockito.Mockito.verify)2