Search in sources :

Example 1 with OAuth2AccessTokenResponseClient

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

the class OAuth2LoginConfigurer method init.

@Override
public void init(B http) throws Exception {
    OAuth2LoginAuthenticationFilter authenticationFilter = new OAuth2LoginAuthenticationFilter(OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(this.getBuilder()), this.loginProcessingUrl);
    this.setAuthenticationFilter(authenticationFilter);
    super.loginProcessingUrl(this.loginProcessingUrl);
    if (this.loginPage != null) {
        // Set custom login page
        super.loginPage(this.loginPage);
        super.init(http);
    } else {
        Map<String, String> loginUrlToClientName = this.getLoginLinks();
        if (loginUrlToClientName.size() == 1) {
            // Setup auto-redirect to provider login page
            // when only 1 client is configured
            this.updateAuthenticationDefaults();
            this.updateAccessDefaults(http);
            String providerLoginPage = loginUrlToClientName.keySet().iterator().next();
            this.registerAuthenticationEntryPoint(http, this.getLoginEntryPoint(http, providerLoginPage));
        } else {
            super.init(http);
        }
    }
    OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = this.tokenEndpointConfig.accessTokenResponseClient;
    if (accessTokenResponseClient == null) {
        accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
    }
    OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = getOAuth2UserService();
    OAuth2LoginAuthenticationProvider oauth2LoginAuthenticationProvider = new OAuth2LoginAuthenticationProvider(accessTokenResponseClient, oauth2UserService);
    GrantedAuthoritiesMapper userAuthoritiesMapper = this.getGrantedAuthoritiesMapper();
    if (userAuthoritiesMapper != null) {
        oauth2LoginAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
    }
    http.authenticationProvider(this.postProcess(oauth2LoginAuthenticationProvider));
    boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
    if (oidcAuthenticationProviderEnabled) {
        OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService = getOidcUserService();
        OidcAuthorizationCodeAuthenticationProvider oidcAuthorizationCodeAuthenticationProvider = new OidcAuthorizationCodeAuthenticationProvider(accessTokenResponseClient, oidcUserService);
        JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = this.getJwtDecoderFactoryBean();
        if (jwtDecoderFactory != null) {
            oidcAuthorizationCodeAuthenticationProvider.setJwtDecoderFactory(jwtDecoderFactory);
        }
        if (userAuthoritiesMapper != null) {
            oidcAuthorizationCodeAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
        }
        http.authenticationProvider(this.postProcess(oidcAuthorizationCodeAuthenticationProvider));
    } else {
        http.authenticationProvider(new OidcAuthenticationRequestChecker());
    }
    this.initDefaultLoginFilter(http);
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OidcAuthorizationCodeAuthenticationProvider(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2LoginAuthenticationFilter(org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter) DefaultAuthorizationCodeTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient) OAuth2LoginAuthenticationProvider(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider)

Example 2 with OAuth2AccessTokenResponseClient

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

the class OAuth2ClientConfigurationTests method requestWhenAuthorizedClientNotFoundAndClientCredentialsThenTokenResponseClientIsUsed.

@Test
public void requestWhenAuthorizedClientNotFoundAndClientCredentialsThenTokenResponseClientIsUsed() throws Exception {
    String clientRegistrationId = "client1";
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().registrationId(clientRegistrationId).build();
    given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
    // @formatter:on
    given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class))).willReturn(accessTokenResponse);
    OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
    this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
    MockHttpServletRequestBuilder authenticatedRequest = get("/authorized-client").with(authentication(authentication));
    // @formatter:off
    this.mockMvc.perform(authenticatedRequest).andExpect(status().isOk()).andExpect(content().string("resolved"));
    // @formatter:on
    verify(accessTokenResponseClient, times(1)).getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class));
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Test(org.junit.jupiter.api.Test)

Example 3 with OAuth2AccessTokenResponseClient

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

the class OAuth2ClientConfigurationTests method requestWhenAuthorizedClientFoundThenMethodArgumentResolved.

@Test
public void requestWhenAuthorizedClientFoundThenMethodArgumentResolved() throws Exception {
    String clientRegistrationId = "client1";
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().registrationId(clientRegistrationId).build();
    given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId))).willReturn(clientRegistration);
    OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
    given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
    given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication), any(HttpServletRequest.class))).willReturn(authorizedClient);
    OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
    given(authorizedClient.getAccessToken()).willReturn(accessToken);
    OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
    this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
    // @formatter:off
    this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk()).andExpect(content().string("resolved"));
    // @formatter:on
    verifyZeroInteractions(accessTokenResponseClient);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Test(org.junit.jupiter.api.Test)

Example 4 with OAuth2AccessTokenResponseClient

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

the class OAuth2AuthorizedClientArgumentResolverTests method resolveArgumentWhenAuthorizedClientNotFoundForClientCredentialsClientThenResolvesFromTokenResponseClient.

@SuppressWarnings("unchecked")
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForClientCredentialsClientThenResolvesFromTokenResponseClient() throws Exception {
    OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    ClientCredentialsOAuth2AuthorizedClientProvider clientCredentialsAuthorizedClientProvider = new ClientCredentialsOAuth2AuthorizedClientProvider();
    clientCredentialsAuthorizedClientProvider.setAccessTokenResponseClient(clientCredentialsTokenResponseClient);
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(clientCredentialsAuthorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
    given(clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))).willReturn(null);
    MethodParameter methodParameter = this.getMethodParameter("clientCredentialsClient", OAuth2AuthorizedClient.class);
    OAuth2AuthorizedClient authorizedClient = (OAuth2AuthorizedClient) this.argumentResolver.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null);
    assertThat(authorizedClient).isNotNull();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.registration2);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
    assertThat(authorizedClient.getAccessToken()).isSameAs(accessTokenResponse.getAccessToken());
    verify(this.authorizedClientRepository).saveAuthorizedClient(eq(authorizedClient), eq(this.authentication), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) MethodParameter(org.springframework.core.MethodParameter) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Example 5 with OAuth2AccessTokenResponseClient

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

the class OAuth2AuthorizedClientArgumentResolverTests method resolveArgumentWhenAuthorizedClientNotFoundForPasswordClientThenResolvesFromTokenResponseClient.

@SuppressWarnings("unchecked")
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForPasswordClientThenResolvesFromTokenResponseClient() throws Exception {
    OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    PasswordOAuth2AuthorizedClientProvider passwordAuthorizedClientProvider = new PasswordOAuth2AuthorizedClientProvider();
    passwordAuthorizedClientProvider.setAccessTokenResponseClient(passwordTokenResponseClient);
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(passwordAuthorizedClientProvider);
    // Set custom contextAttributesMapper
    authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
        Map<String, Object> contextAttributes = new HashMap<>();
        HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
        String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
        String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
            contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
        }
        return contextAttributes;
    });
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
    given(passwordTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))).willReturn(null);
    MethodParameter methodParameter = this.getMethodParameter("passwordClient", OAuth2AuthorizedClient.class);
    this.request.setParameter(OAuth2ParameterNames.USERNAME, "username");
    this.request.setParameter(OAuth2ParameterNames.PASSWORD, "password");
    OAuth2AuthorizedClient authorizedClient = (OAuth2AuthorizedClient) this.argumentResolver.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null);
    assertThat(authorizedClient).isNotNull();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.registration3);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
    assertThat(authorizedClient.getAccessToken()).isSameAs(accessTokenResponse.getAccessToken());
    verify(this.authorizedClientRepository).saveAuthorizedClient(eq(authorizedClient), eq(this.authentication), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HashMap(java.util.HashMap) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) PasswordOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider) MethodParameter(org.springframework.core.MethodParameter) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)4 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)3 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)3 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)3 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)3 DefaultOAuth2AuthorizedClientManager (org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager)3 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 MethodParameter (org.springframework.core.MethodParameter)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)2 ClientCredentialsOAuth2AuthorizedClientProvider (org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider)2 OAuth2AccessTokenResponseClient (org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient)2 OAuth2ClientCredentialsGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest)2 ClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)2 OAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository)2 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)2 HashMap (java.util.HashMap)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1