Search in sources :

Example 96 with RegisteredClient

use of org.springframework.security.oauth2.server.authorization.client.RegisteredClient in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeGrantTests method requestWhenPublicClientWithPkceThenReturnAccessTokenResponse.

@Test
public void requestWhenPublicClientWithPkceThenReturnAccessTokenResponse() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.class).autowire();
    RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build();
    this.registeredClientRepository.save(registeredClient);
    MvcResult mvcResult = this.mvc.perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).params(getAuthorizationRequestParameters(registeredClient)).param(PkceParameterNames.CODE_CHALLENGE, S256_CODE_CHALLENGE).param(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256").with(user("user"))).andExpect(status().is3xxRedirection()).andReturn();
    String redirectedUrl = mvcResult.getResponse().getRedirectedUrl();
    assertThat(redirectedUrl).matches("https://example.com\\?code=.{15,}&state=state");
    String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code");
    OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE);
    assertThat(authorizationCodeAuthorization).isNotNull();
    assertThat(authorizationCodeAuthorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)).param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()).param(PkceParameterNames.CODE_VERIFIER, S256_CODE_VERIFIER)).andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))).andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))).andExpect(status().isOk()).andExpect(jsonPath("$.access_token").isNotEmpty()).andExpect(jsonPath("$.token_type").isNotEmpty()).andExpect(jsonPath("$.expires_in").isNotEmpty()).andExpect(jsonPath("$.refresh_token").doesNotExist()).andExpect(jsonPath("$.scope").isNotEmpty());
    OAuth2Authorization accessTokenAuthorization = this.authorizationService.findById(authorizationCodeAuthorization.getId());
    assertThat(accessTokenAuthorization).isNotNull();
    assertThat(accessTokenAuthorization.getAccessToken()).isNotNull();
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = accessTokenAuthorization.getToken(OAuth2AuthorizationCode.class);
    assertThat(authorizationCodeToken).isNotNull();
    assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)).isEqualTo(true);
}
Also used : OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) MvcResult(org.springframework.test.web.servlet.MvcResult) OAuth2AuthorizationServerConfiguration(org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 97 with RegisteredClient

use of org.springframework.security.oauth2.server.authorization.client.RegisteredClient in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeGrantTests method requestWhenConsentRequestThenReturnAccessTokenResponse.

@Test
public void requestWhenConsentRequestThenReturnAccessTokenResponse() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.class).autowire();
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
        scopes.clear();
        scopes.add("message.read");
        scopes.add("message.write");
    }).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build();
    this.registeredClientRepository.save(registeredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).principalName("user").build();
    this.authorizationService.save(authorization);
    MvcResult mvcResult = this.mvc.perform(post(DEFAULT_AUTHORIZATION_ENDPOINT_URI).param(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()).param(OAuth2ParameterNames.SCOPE, "message.read").param(OAuth2ParameterNames.SCOPE, "message.write").param(OAuth2ParameterNames.STATE, "state").with(user("user"))).andExpect(status().is3xxRedirection()).andReturn();
    String redirectedUrl = mvcResult.getResponse().getRedirectedUrl();
    assertThat(redirectedUrl).matches("https://example.com\\?code=.{15,}&state=state");
    String authorizationCode = extractParameterFromRedirectUri(redirectedUrl, "code");
    OAuth2Authorization authorizationCodeAuthorization = this.authorizationService.findByToken(authorizationCode, AUTHORIZATION_CODE_TOKEN_TYPE);
    this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(getTokenRequestParameters(registeredClient, authorizationCodeAuthorization)).header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))).andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))).andExpect(jsonPath("$.access_token").isNotEmpty()).andExpect(jsonPath("$.token_type").isNotEmpty()).andExpect(jsonPath("$.expires_in").isNotEmpty()).andExpect(jsonPath("$.refresh_token").isNotEmpty()).andExpect(jsonPath("$.scope").isNotEmpty()).andReturn();
}
Also used : OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) MvcResult(org.springframework.test.web.servlet.MvcResult) OAuth2AuthorizationServerConfiguration(org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 98 with RegisteredClient

use of org.springframework.security.oauth2.server.authorization.client.RegisteredClient in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeGrantTests method assertTokenRequestReturnsAccessTokenResponse.

private OAuth2AccessTokenResponse assertTokenRequestReturnsAccessTokenResponse(RegisteredClient registeredClient, OAuth2Authorization authorization, String tokenEndpointUri) throws Exception {
    MvcResult mvcResult = this.mvc.perform(post(tokenEndpointUri).params(getTokenRequestParameters(registeredClient, authorization)).header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(registeredClient))).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))).andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))).andExpect(jsonPath("$.access_token").isNotEmpty()).andExpect(jsonPath("$.token_type").isNotEmpty()).andExpect(jsonPath("$.expires_in").isNotEmpty()).andExpect(jsonPath("$.refresh_token").isNotEmpty()).andExpect(jsonPath("$.scope").isNotEmpty()).andReturn();
    OAuth2Authorization accessTokenAuthorization = this.authorizationService.findById(authorization.getId());
    assertThat(accessTokenAuthorization).isNotNull();
    assertThat(accessTokenAuthorization.getAccessToken()).isNotNull();
    assertThat(accessTokenAuthorization.getRefreshToken()).isNotNull();
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCodeToken = accessTokenAuthorization.getToken(OAuth2AuthorizationCode.class);
    assertThat(authorizationCodeToken).isNotNull();
    assertThat(authorizationCodeToken.getMetadata().get(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME)).isEqualTo(true);
    MockHttpServletResponse servletResponse = mvcResult.getResponse();
    MockClientHttpResponse httpResponse = new MockClientHttpResponse(servletResponse.getContentAsByteArray(), HttpStatus.valueOf(servletResponse.getStatus()));
    return accessTokenHttpResponseConverter.read(OAuth2AccessTokenResponse.class, httpResponse);
}
Also used : OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) MvcResult(org.springframework.test.web.servlet.MvcResult) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockClientHttpResponse(org.springframework.mock.http.client.MockClientHttpResponse)

Example 99 with RegisteredClient

use of org.springframework.security.oauth2.server.authorization.client.RegisteredClient in project spring-authorization-server by spring-projects.

the class OAuth2ClientCredentialsGrantTests method requestWhenTokenEndpointCustomizedThenUsed.

@Test
public void requestWhenTokenEndpointCustomizedThenUsed() throws Exception {
    this.spring.register(AuthorizationServerConfigurationCustomTokenEndpoint.class).autowire();
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
    this.registeredClientRepository.save(registeredClient);
    OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
    when(authenticationConverter.convert(any())).thenReturn(clientCredentialsAuthentication);
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)));
    OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
    when(authenticationProvider.supports(eq(OAuth2ClientCredentialsAuthenticationToken.class))).thenReturn(true);
    when(authenticationProvider.authenticate(any())).thenReturn(accessTokenAuthentication);
    this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()).header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()))).andExpect(status().isOk());
    verify(authenticationConverter).convert(any());
    verify(authenticationProvider).authenticate(eq(clientCredentialsAuthentication));
    verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), eq(accessTokenAuthentication));
}
Also used : OAuth2ClientCredentialsAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken) OAuth2AccessTokenAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 100 with RegisteredClient

use of org.springframework.security.oauth2.server.authorization.client.RegisteredClient in project spring-authorization-server by spring-projects.

the class OAuth2RefreshTokenGrantTests method requestWhenRevokeAndRefreshThenAccessTokenActive.

// gh-432
@Test
public void requestWhenRevokeAndRefreshThenAccessTokenActive() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.class).autowire();
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    this.registeredClientRepository.save(registeredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
    this.authorizationService.save(authorization);
    OAuth2AccessToken token = authorization.getAccessToken().getToken();
    OAuth2TokenType tokenType = OAuth2TokenType.ACCESS_TOKEN;
    this.mvc.perform(post(DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI).params(getTokenRevocationRequestParameters(token, tokenType)).header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()))).andExpect(status().isOk());
    this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(getRefreshTokenRequestParameters(authorization)).header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()))).andExpect(status().isOk());
    OAuth2Authorization updatedAuthorization = this.authorizationService.findById(authorization.getId());
    OAuth2Authorization.Token<OAuth2AccessToken> accessToken = updatedAuthorization.getAccessToken();
    assertThat(accessToken.isActive()).isTrue();
}
Also used : OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2AuthorizationServerConfiguration(org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Aggregations

RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)223 Test (org.junit.Test)189 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)127 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)68 Authentication (org.springframework.security.core.Authentication)59 Instant (java.time.Instant)55 Jwt (org.springframework.security.oauth2.jwt.Jwt)52 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)50 OAuth2TokenType (org.springframework.security.oauth2.core.OAuth2TokenType)48 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)46 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)45 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)44 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)44 OAuth2ErrorCodes (org.springframework.security.oauth2.core.OAuth2ErrorCodes)44 TestRegisteredClients (org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients)44 Before (org.junit.Before)41 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)41 Mockito.mock (org.mockito.Mockito.mock)41 Mockito.verify (org.mockito.Mockito.verify)41 Mockito.when (org.mockito.Mockito.when)41