Search in sources :

Example 1 with ClientRegistrationRepository

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

the class OAuth2ClientConfigurerUtils method getClientRegistrationRepository.

static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B builder) {
    ClientRegistrationRepository clientRegistrationRepository = builder.getSharedObject(ClientRegistrationRepository.class);
    if (clientRegistrationRepository == null) {
        clientRegistrationRepository = getClientRegistrationRepositoryBean(builder);
        builder.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
    }
    return clientRegistrationRepository;
}
Also used : ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)

Example 2 with ClientRegistrationRepository

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

the class OAuth2LoginConfigurer method getLoginLinks.

@SuppressWarnings("unchecked")
private Map<String, String> getLoginLinks() {
    Iterable<ClientRegistration> clientRegistrations = null;
    ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder());
    ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
    if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
        clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
    }
    if (clientRegistrations == null) {
        return Collections.emptyMap();
    }
    String authorizationRequestBaseUri = (this.authorizationEndpointConfig.authorizationRequestBaseUri != null) ? this.authorizationEndpointConfig.authorizationRequestBaseUri : OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
    Map<String, String> loginUrlToClientName = new HashMap<>();
    clientRegistrations.forEach((registration) -> {
        if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(registration.getAuthorizationGrantType())) {
            String authorizationRequestUri = authorizationRequestBaseUri + "/" + registration.getRegistrationId();
            loginUrlToClientName.put(authorizationRequestUri, registration.getClientName());
        }
    });
    return loginUrlToClientName;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) ResolvableType(org.springframework.core.ResolvableType)

Example 3 with ClientRegistrationRepository

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

the class OAuth2ClientBeanDefinitionParser method parse.

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    Element authorizationCodeGrantElt = DomUtils.getChildElementByTagName(element, ELT_AUTHORIZATION_CODE_GRANT);
    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 authorizationRequestRepository = getAuthorizationRequestRepository(authorizationCodeGrantElt);
    BeanDefinitionBuilder authorizationRequestRedirectFilterBuilder = BeanDefinitionBuilder.rootBeanDefinition(OAuth2AuthorizationRequestRedirectFilter.class);
    String authorizationRequestResolverRef = (authorizationCodeGrantElt != null) ? authorizationCodeGrantElt.getAttribute(ATT_AUTHORIZATION_REQUEST_RESOLVER_REF) : null;
    if (!StringUtils.isEmpty(authorizationRequestResolverRef)) {
        authorizationRequestRedirectFilterBuilder.addConstructorArgReference(authorizationRequestResolverRef);
    } else {
        authorizationRequestRedirectFilterBuilder.addConstructorArgValue(clientRegistrationRepository);
    }
    this.authorizationRequestRedirectFilter = authorizationRequestRedirectFilterBuilder.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository).addPropertyValue("requestCache", this.requestCache).getBeanDefinition();
    this.authorizationCodeGrantFilter = BeanDefinitionBuilder.rootBeanDefinition(OAuth2AuthorizationCodeGrantFilter.class).addConstructorArgValue(clientRegistrationRepository).addConstructorArgValue(authorizedClientRepository).addConstructorArgValue(this.authenticationManager).addPropertyValue("authorizationRequestRepository", authorizationRequestRepository).getBeanDefinition();
    BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(authorizationCodeGrantElt);
    this.authorizationCodeAuthenticationProvider = BeanDefinitionBuilder.rootBeanDefinition(OAuth2AuthorizationCodeAuthenticationProvider.class).addConstructorArgValue(accessTokenResponseClient).getBeanDefinition();
    return null;
}
Also used : BeanMetadataElement(org.springframework.beans.BeanMetadataElement) OAuth2AuthorizationCodeAuthenticationProvider(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationProvider) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) Element(org.w3c.dom.Element) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository)

Example 4 with ClientRegistrationRepository

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

the class InMemoryOAuth2AuthorizedClientServiceTests method constructorWhenAuthorizedClientsProvidedThenUseProvidedAuthorizedClients.

@Test
public void constructorWhenAuthorizedClientsProvidedThenUseProvidedAuthorizedClients() {
    String registrationId = this.registration3.getRegistrationId();
    Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients = Collections.singletonMap(new OAuth2AuthorizedClientId(this.registration3.getRegistrationId(), this.principalName1), mock(OAuth2AuthorizedClient.class));
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    given(clientRegistrationRepository.findByRegistrationId(eq(registrationId))).willReturn(this.registration3);
    InMemoryOAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository, authorizedClients);
    assertThatObject(authorizedClientService.loadAuthorizedClient(registrationId, this.principalName1)).isNotNull();
}
Also used : InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) Test(org.junit.jupiter.api.Test)

Example 5 with ClientRegistrationRepository

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

the class ServerHttpSecurityTests method shouldConfigureRequestCacheForOAuth2LoginAuthenticationEntryPointAndSuccessHandler.

@Test
public void shouldConfigureRequestCacheForOAuth2LoginAuthenticationEntryPointAndSuccessHandler() {
    ServerRequestCache requestCache = spy(new WebSessionServerRequestCache());
    ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
    SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).and().authorizeExchange().anyExchange().authenticated().and().requestCache((c) -> c.requestCache(requestCache)).build();
    WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
    client.get().uri("/test").exchange();
    ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);
    verify(requestCache).saveRequest(captor.capture());
    assertThat(captor.getValue().getRequest().getURI().toString()).isEqualTo("/test");
    OAuth2LoginAuthenticationWebFilter authenticationWebFilter = getWebFilter(securityFilterChain, OAuth2LoginAuthenticationWebFilter.class).get();
    Object handler = ReflectionTestUtils.getField(authenticationWebFilter, "authenticationSuccessHandler");
    assertThat(ReflectionTestUtils.getField(handler, "requestCache")).isSameAs(requestCache);
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ServerLogoutHandler(org.springframework.security.web.server.authentication.logout.ServerLogoutHandler) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) LogoutWebFilter(org.springframework.security.web.server.authentication.logout.LogoutWebFilter) WebFilter(org.springframework.web.server.WebFilter) BDDMockito.given(org.mockito.BDDMockito.given) HttpBasicServerAuthenticationEntryPoint(org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) WebSessionServerSecurityContextRepository(org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository) HttpHeaders(org.apache.http.HttpHeaders) OAuth2LoginAuthenticationWebFilter(org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter) WebFilterChain(org.springframework.web.server.WebFilterChain) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ServerHttpSecurityConfigurationBuilder(org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder) ServerAuthenticationEntryPoint(org.springframework.security.web.server.ServerAuthenticationEntryPoint) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) EntityExchangeResult(org.springframework.test.web.reactive.server.EntityExchangeResult) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) SecurityContext(org.springframework.security.core.context.SecurityContext) Optional(java.util.Optional) CsrfWebFilter(org.springframework.security.web.server.csrf.CsrfWebFilter) Authentication(org.springframework.security.core.Authentication) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) TestPublisher(reactor.test.publisher.TestPublisher) Mock(org.mockito.Mock) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) Mockito.spy(org.mockito.Mockito.spy) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) SecurityContextServerLogoutHandler(org.springframework.security.web.server.authentication.logout.SecurityContextServerLogoutHandler) ArgumentCaptor(org.mockito.ArgumentCaptor) WebSessionServerRequestCache(org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache) GetMapping(org.springframework.web.bind.annotation.GetMapping) AnonymousAuthenticationWebFilterTests(org.springframework.security.web.server.authentication.AnonymousAuthenticationWebFilterTests) WebTestClientBuilder(org.springframework.security.test.web.reactive.server.WebTestClientBuilder) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) X509PrincipalExtractor(org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mono(reactor.core.publisher.Mono) WebFilterChainProxy(org.springframework.security.web.server.WebFilterChainProxy) CsrfServerLogoutHandler(org.springframework.security.web.server.csrf.CsrfServerLogoutHandler) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) FluxExchangeResult(org.springframework.test.web.reactive.server.FluxExchangeResult) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) HttpStatusServerEntryPoint(org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint) ServerCsrfTokenRepository(org.springframework.security.web.server.csrf.ServerCsrfTokenRepository) ServerX509AuthenticationConverter(org.springframework.security.web.server.authentication.ServerX509AuthenticationConverter) DelegatingServerLogoutHandler(org.springframework.security.web.server.authentication.logout.DelegatingServerLogoutHandler) Customizer.withDefaults(org.springframework.security.config.Customizer.withDefaults) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) OAuth2LoginAuthenticationWebFilter(org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) WebSessionServerRequestCache(org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache) WebSessionServerRequestCache(org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)7 ClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)7 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)6 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)4 OAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository)4 OAuth2AccessTokenResponseClient (org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient)3 InMemoryClientRegistrationRepository (org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository)3 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 BeforeEach (org.junit.jupiter.api.BeforeEach)2 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)2 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)2 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)2 ResolvableType (org.springframework.core.ResolvableType)2 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)2 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)2 ReactiveClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository)2 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 Arrays (java.util.Arrays)1