Search in sources :

Example 1 with ClientAuthenticationMethod

use of org.springframework.security.oauth2.core.ClientAuthenticationMethod in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method setup.

@BeforeEach
public void setup() {
    this.authentication = new TestingAuthenticationToken(this.principalName, "password");
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(this.authentication);
    SecurityContextHolder.setContext(securityContext);
    // @formatter:off
    this.registration1 = ClientRegistration.withRegistrationId("client1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    this.registration2 = ClientRegistration.withRegistrationId("client2").clientId("client-2").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope("read", "write").tokenUri("https://provider.com/oauth2/token").build();
    this.registration3 = TestClientRegistrations.password().registrationId("client3").build();
    // @formatter:on
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2, this.registration3);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken().clientCredentials().build();
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1);
    this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) PasswordOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider) ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with ClientAuthenticationMethod

use of org.springframework.security.oauth2.core.ClientAuthenticationMethod in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenJwtBearerClientNotAuthorizedThenExchangeToken.

@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    ClientRegistration registration = ClientRegistration.withRegistrationId("jwt-bearer").clientId("client-id").clientSecret("client-secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").tokenUri("https://example.com/oauth/token").build();
    // @formatter:on
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(registration);
    Jwt jwtAssertion = TestJwts.jwt().build();
    Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(jwtAuthentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)).build();
    this.function.filter(request, this.exchange).block();
    verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), any(), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer exchanged-token");
    assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request1.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request1)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 3 with ClientAuthenticationMethod

use of org.springframework.security.oauth2.core.ClientAuthenticationMethod in project spring-security by spring-projects.

the class DefaultServerOAuth2AuthorizationRequestResolverTests method resolveWhenAuthorizationRequestWithValidPkceClientThenResolves.

@Test
public void resolveWhenAuthorizationRequestWithValidPkceClientThenResolves() {
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build()));
    OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
    assertThat((String) request.getAttribute(PkceParameterNames.CODE_VERIFIER)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
    assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&" + "code_challenge_method=S256&" + "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}");
}
Also used : OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 4 with ClientAuthenticationMethod

use of org.springframework.security.oauth2.core.ClientAuthenticationMethod in project spring-security by spring-projects.

the class ClientRegistrations method withProviderConfiguration.

private static ClientRegistration.Builder withProviderConfiguration(AuthorizationServerMetadata metadata, String issuer) {
    String metadataIssuer = metadata.getIssuer().getValue();
    Assert.state(issuer.equals(metadataIssuer), () -> "The Issuer \"" + metadataIssuer + "\" provided in the configuration metadata did " + "not match the requested issuer \"" + issuer + "\"");
    String name = URI.create(issuer).getHost();
    ClientAuthenticationMethod method = getClientAuthenticationMethod(metadata.getTokenEndpointAuthMethods());
    Map<String, Object> configurationMetadata = new LinkedHashMap<>(metadata.toJSONObject());
    // @formatter:off
    return ClientRegistration.withRegistrationId(name).userNameAttributeName(IdTokenClaimNames.SUB).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).clientAuthenticationMethod(method).redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}").authorizationUri((metadata.getAuthorizationEndpointURI() != null) ? metadata.getAuthorizationEndpointURI().toASCIIString() : null).providerConfigurationMetadata(configurationMetadata).tokenUri(metadata.getTokenEndpointURI().toASCIIString()).issuerUri(issuer).clientName(issuer);
// @formatter:on
}
Also used : ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) JSONObject(net.minidev.json.JSONObject) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with ClientAuthenticationMethod

use of org.springframework.security.oauth2.core.ClientAuthenticationMethod in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantRequestEntityConverterTests method convertWhenPkceGrantRequestValidThenConverts.

@SuppressWarnings("unchecked")
@Test
public void convertWhenPkceGrantRequestValidThenConverts() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().clientAuthenticationMethod(null).clientSecret(null).build();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(PkceParameterNames.CODE_VERIFIER, "code-verifier-1234");
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge-1234");
    additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().attributes(attributes).additionalParameters(additionalParameters).build();
    OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authorizationExchange);
    RequestEntity<?> requestEntity = this.converter.convert(authorizationCodeGrantRequest);
    assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
    assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
    HttpHeaders headers = requestEntity.getHeaders();
    assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
    assertThat(headers.getContentType()).isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
    assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).isNull();
    MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
    assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.CODE)).isEqualTo(authorizationResponse.getCode());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI)).isEqualTo(authorizationRequest.getRedirectUri());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.CLIENT_ID)).isEqualTo(authorizationRequest.getClientId());
    assertThat(formParameters.getFirst(PkceParameterNames.CODE_VERIFIER)).isEqualTo(authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HashMap(java.util.HashMap) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)12 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)11 BeforeEach (org.junit.jupiter.api.BeforeEach)7 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)5 InMemoryClientRegistrationRepository (org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository)4 Jwt (org.springframework.security.oauth2.jwt.Jwt)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 Authentication (org.springframework.security.core.Authentication)3 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)3 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)3 RSAKey (com.nimbusds.jose.jwk.RSAKey)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 OAuth2AccessTokenResponseClient (org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient)2 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)2 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)2 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)2 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 OctetSequenceKey (com.nimbusds.jose.jwk.OctetSequenceKey)1 FilterChain (jakarta.servlet.FilterChain)1