Search in sources :

Example 16 with OAuth2PasswordGrantRequest

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

the class DefaultPasswordTokenResponseClientTests method getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    JWK jwk = TestJwks.DEFAULT_RSA_JWK;
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
    this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
    RecordedRequest recordedRequest = this.server.takeRequest();
    assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    String formParameters = recordedRequest.getBody().readUtf8();
    assertThat(formParameters).contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
    assertThat(formParameters).contains("client_assertion=");
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 17 with OAuth2PasswordGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest 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)

Example 18 with OAuth2PasswordGrantRequest

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

the class OAuth2PasswordGrantRequestEntityConverter method createParameters.

@Override
protected MultiValueMap<String, String> createParameters(OAuth2PasswordGrantRequest passwordGrantRequest) {
    ClientRegistration clientRegistration = passwordGrantRequest.getClientRegistration();
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.add(OAuth2ParameterNames.GRANT_TYPE, passwordGrantRequest.getGrantType().getValue());
    parameters.add(OAuth2ParameterNames.USERNAME, passwordGrantRequest.getUsername());
    parameters.add(OAuth2ParameterNames.PASSWORD, passwordGrantRequest.getPassword());
    if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
        parameters.add(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
    }
    if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) {
        parameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
        parameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
    }
    return parameters;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 19 with OAuth2PasswordGrantRequest

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

the class OAuth2PasswordGrantRequestEntityConverterTests method convertWhenParametersConverterSetThenCalled.

@Test
public void convertWhenParametersConverterSetThenCalled() {
    Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(Converter.class);
    this.converter.setParametersConverter(parametersConverter1);
    Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(Converter.class);
    this.converter.addParametersConverter(parametersConverter2);
    ClientRegistration clientRegistration = TestClientRegistrations.password().build();
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, "user1", "password");
    this.converter.convert(passwordGrantRequest);
    InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
    inOrder.verify(parametersConverter1).convert(any(OAuth2PasswordGrantRequest.class));
    inOrder.verify(parametersConverter2).convert(any(OAuth2PasswordGrantRequest.class));
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) InOrder(org.mockito.InOrder) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Example 20 with OAuth2PasswordGrantRequest

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

the class OAuth2PasswordGrantRequestEntityConverterTests method convertWhenHeadersConverterSetThenCalled.

@Test
public void convertWhenHeadersConverterSetThenCalled() {
    Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
    this.converter.setHeadersConverter(headersConverter1);
    Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
    this.converter.addHeadersConverter(headersConverter2);
    ClientRegistration clientRegistration = TestClientRegistrations.password().build();
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, "user1", "password");
    this.converter.convert(passwordGrantRequest);
    InOrder inOrder = inOrder(headersConverter1, headersConverter2);
    inOrder.verify(headersConverter1).convert(any(OAuth2PasswordGrantRequest.class));
    inOrder.verify(headersConverter2).convert(any(OAuth2PasswordGrantRequest.class));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) InOrder(org.mockito.InOrder) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)17 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)17 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)12 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)11 Instant (java.time.Instant)7 HttpHeaders (org.springframework.http.HttpHeaders)7 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)5 JWK (com.nimbusds.jose.jwk.JWK)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Function (java.util.function.Function)4 SecretKeySpec (javax.crypto.spec.SecretKeySpec)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 MockWebServer (okhttp3.mockwebserver.MockWebServer)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)4 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)4 AfterEach (org.junit.jupiter.api.AfterEach)4 BeforeEach (org.junit.jupiter.api.BeforeEach)4 HttpMethod (org.springframework.http.HttpMethod)4 MediaType (org.springframework.http.MediaType)4