Search in sources :

Example 1 with OAuth2AuthorizationCode

use of org.springframework.security.oauth2.core.OAuth2AuthorizationCode in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeRequestAuthenticationProviderTests method authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException.

@Test
public void authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    @SuppressWarnings("unchecked") OAuth2TokenGenerator<OAuth2AuthorizationCode> authorizationCodeGenerator = mock(OAuth2TokenGenerator.class);
    this.authenticationProvider.setAuthorizationCodeGenerator(authorizationCodeGenerator);
    OAuth2AuthorizationCodeRequestAuthenticationToken authentication = authorizationCodeRequestAuthentication(registeredClient, this.principal).build();
    assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)).isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class).extracting(ex -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError()).satisfies(error -> {
        assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
        assertThat(error.getDescription()).contains("The token generator failed to generate the authorization code.");
    });
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) PkceParameterNames(org.springframework.security.oauth2.core.endpoint.PkceParameterNames) OAuth2TokenGenerator(org.springframework.security.oauth2.server.authorization.OAuth2TokenGenerator) OAuth2AuthorizationResponseType(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) Supplier(java.util.function.Supplier) OAuth2AuthorizationConsentService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService) HashSet(java.util.HashSet) TestOAuth2Authorizations(org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Map(java.util.Map) OidcScopes(org.springframework.security.oauth2.core.oidc.OidcScopes) OAuth2AuthenticationValidator(org.springframework.security.oauth2.core.authentication.OAuth2AuthenticationValidator) ClientSettings(org.springframework.security.oauth2.server.authorization.config.ClientSettings) Before(org.junit.Before) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) ProviderSettings(org.springframework.security.oauth2.server.authorization.config.ProviderSettings) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2AuthorizationConsent(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Set(java.util.Set) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) TestRegisteredClients(org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients) OAuth2AuthorizationService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) ProviderContextHolder(org.springframework.security.oauth2.server.authorization.context.ProviderContextHolder) Mockito.never(org.mockito.Mockito.never) Principal(java.security.Principal) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ProviderContext(org.springframework.security.oauth2.server.authorization.context.ProviderContext) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 2 with OAuth2AuthorizationCode

use of org.springframework.security.oauth2.core.OAuth2AuthorizationCode in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeAuthenticationProviderTests method authenticateWhenValidCodeAndAuthenticationRequestThenReturnIdToken.

@Test
public void authenticateWhenValidCodeAndAuthenticationRequestThenReturnIdToken() {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
    when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))).thenReturn(authorization);
    OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
    when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt());
    OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
    ArgumentCaptor<JwtEncodingContext> jwtEncodingContextCaptor = ArgumentCaptor.forClass(JwtEncodingContext.class);
    verify(this.jwtCustomizer, times(2)).customize(jwtEncodingContextCaptor.capture());
    // Access Token context
    JwtEncodingContext accessTokenContext = jwtEncodingContextCaptor.getAllValues().get(0);
    assertThat(accessTokenContext.getRegisteredClient()).isEqualTo(registeredClient);
    assertThat(accessTokenContext.<Authentication>getPrincipal()).isEqualTo(authorization.getAttribute(Principal.class.getName()));
    assertThat(accessTokenContext.getAuthorization()).isEqualTo(authorization);
    assertThat(accessTokenContext.getAuthorizedScopes()).isEqualTo(authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME));
    assertThat(accessTokenContext.getTokenType()).isEqualTo(OAuth2TokenType.ACCESS_TOKEN);
    assertThat(accessTokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    assertThat(accessTokenContext.<OAuth2AuthorizationGrantAuthenticationToken>getAuthorizationGrant()).isEqualTo(authentication);
    assertThat(accessTokenContext.getHeaders()).isNotNull();
    assertThat(accessTokenContext.getClaims()).isNotNull();
    Map<String, Object> claims = new HashMap<>();
    accessTokenContext.getClaims().claims(claims::putAll);
    assertThat(claims).flatExtracting(OAuth2ParameterNames.SCOPE).containsExactlyInAnyOrder(OidcScopes.OPENID, "scope1");
    // ID Token context
    JwtEncodingContext idTokenContext = jwtEncodingContextCaptor.getAllValues().get(1);
    assertThat(idTokenContext.getRegisteredClient()).isEqualTo(registeredClient);
    assertThat(idTokenContext.<Authentication>getPrincipal()).isEqualTo(authorization.getAttribute(Principal.class.getName()));
    assertThat(idTokenContext.getAuthorization()).isEqualTo(authorization);
    assertThat(idTokenContext.getAuthorizedScopes()).isEqualTo(authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME));
    assertThat(idTokenContext.getTokenType().getValue()).isEqualTo(OidcParameterNames.ID_TOKEN);
    assertThat(idTokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    assertThat(idTokenContext.<OAuth2AuthorizationGrantAuthenticationToken>getAuthorizationGrant()).isEqualTo(authentication);
    assertThat(idTokenContext.getHeaders()).isNotNull();
    assertThat(idTokenContext.getClaims()).isNotNull();
    // Access token and ID Token
    verify(this.jwtEncoder, times(2)).encode(any(), any());
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
    verify(this.authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
    assertThat(accessTokenAuthentication.getRegisteredClient().getId()).isEqualTo(updatedAuthorization.getRegisteredClientId());
    assertThat(accessTokenAuthentication.getPrincipal()).isEqualTo(clientPrincipal);
    assertThat(accessTokenAuthentication.getAccessToken()).isEqualTo(updatedAuthorization.getAccessToken().getToken());
    Set<String> accessTokenScopes = new HashSet<>(updatedAuthorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME));
    assertThat(accessTokenAuthentication.getAccessToken().getScopes()).isEqualTo(accessTokenScopes);
    assertThat(accessTokenAuthentication.getRefreshToken()).isNotNull();
    assertThat(accessTokenAuthentication.getRefreshToken()).isEqualTo(updatedAuthorization.getRefreshToken().getToken());
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = updatedAuthorization.getToken(OAuth2AuthorizationCode.class);
    assertThat(authorizationCode.isInvalidated()).isTrue();
    OAuth2Authorization.Token<OidcIdToken> idToken = updatedAuthorization.getToken(OidcIdToken.class);
    assertThat(idToken).isNotNull();
    assertThat(accessTokenAuthentication.getAdditionalParameters()).containsExactly(entry(OidcParameterNames.ID_TOKEN, idToken.getToken().getTokenValue()));
}
Also used : OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) HashMap(java.util.HashMap) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) JwtEncodingContext(org.springframework.security.oauth2.server.authorization.JwtEncodingContext) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 3 with OAuth2AuthorizationCode

use of org.springframework.security.oauth2.core.OAuth2AuthorizationCode in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeRequestAuthenticationProviderTests method assertAuthorizationCodeRequestWithAuthorizationCodeResult.

private void assertAuthorizationCodeRequestWithAuthorizationCodeResult(RegisteredClient registeredClient, OAuth2AuthorizationCodeRequestAuthenticationToken authentication, OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult) {
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
    verify(this.authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization authorization = authorizationCaptor.getValue();
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
    assertThat(authorizationRequest.getAuthorizationUri()).isEqualTo(authentication.getAuthorizationUri());
    assertThat(authorizationRequest.getClientId()).isEqualTo(registeredClient.getClientId());
    assertThat(authorizationRequest.getRedirectUri()).isEqualTo(authentication.getRedirectUri());
    assertThat(authorizationRequest.getScopes()).isEqualTo(authentication.getScopes());
    assertThat(authorizationRequest.getState()).isEqualTo(authentication.getState());
    assertThat(authorizationRequest.getAdditionalParameters()).isEqualTo(authentication.getAdditionalParameters());
    assertThat(authorization.getRegisteredClientId()).isEqualTo(registeredClient.getId());
    assertThat(authorization.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    assertThat(authorization.<Authentication>getAttribute(Principal.class.getName())).isEqualTo(this.principal);
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class);
    Set<String> authorizedScopes = authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
    assertThat(authenticationResult.getClientId()).isEqualTo(registeredClient.getClientId());
    assertThat(authenticationResult.getPrincipal()).isEqualTo(this.principal);
    assertThat(authenticationResult.getAuthorizationUri()).isEqualTo(authorizationRequest.getAuthorizationUri());
    assertThat(authenticationResult.getRedirectUri()).isEqualTo(authorizationRequest.getRedirectUri());
    assertThat(authenticationResult.getScopes()).isEqualTo(authorizedScopes);
    assertThat(authenticationResult.getState()).isEqualTo(authorizationRequest.getState());
    assertThat(authenticationResult.getAuthorizationCode()).isEqualTo(authorizationCode.getToken());
    assertThat(authenticationResult.isAuthenticated()).isTrue();
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Principal(java.security.Principal)

Example 4 with OAuth2AuthorizationCode

use of org.springframework.security.oauth2.core.OAuth2AuthorizationCode in project spring-authorization-server by spring-projects.

the class TestOAuth2Authorizations method authorization.

private static OAuth2Authorization.Builder authorization(RegisteredClient registeredClient, OAuth2AccessToken accessToken, Map<String, Object> accessTokenClaims, Map<String, Object> authorizationRequestAdditionalParameters) {
    OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode("code", Instant.now(), Instant.now().plusSeconds(120));
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", Instant.now(), Instant.now().plus(1, ChronoUnit.HOURS));
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().authorizationUri("https://provider.com/oauth2/authorize").clientId(registeredClient.getClientId()).redirectUri(registeredClient.getRedirectUris().iterator().next()).scopes(registeredClient.getScopes()).additionalParameters(authorizationRequestAdditionalParameters).state("state").build();
    return OAuth2Authorization.withRegisteredClient(registeredClient).id("id").principalName("principal").authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).token(authorizationCode).token(accessToken, (metadata) -> metadata.putAll(tokenMetadata(accessTokenClaims))).refreshToken(refreshToken).attribute(OAuth2ParameterNames.STATE, "state").attribute(OAuth2AuthorizationRequest.class.getName(), authorizationRequest).attribute(Principal.class.getName(), new TestingAuthenticationToken("principal", null, "ROLE_A", "ROLE_B")).attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizationRequest.getScopes());
}
Also used : OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) HashMap(java.util.HashMap) Instant(java.time.Instant) TestRegisteredClients(org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients) Principal(java.security.Principal) ChronoUnit(java.time.temporal.ChronoUnit) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) CollectionUtils(org.springframework.util.CollectionUtils) Map(java.util.Map) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 5 with OAuth2AuthorizationCode

use of org.springframework.security.oauth2.core.OAuth2AuthorizationCode in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeAuthenticationProviderTests method authenticateWhenExpiredCodeThenThrowOAuth2AuthenticationException.

// gh-290
@Test
public void authenticateWhenExpiredCodeThenThrowOAuth2AuthenticationException() {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode(AUTHORIZATION_CODE, Instant.now().minusSeconds(300), Instant.now().minusSeconds(60));
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).token(authorizationCode).build();
    when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))).thenReturn(authorization);
    OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
    assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)).isInstanceOf(OAuth2AuthenticationException.class).extracting(ex -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode").isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
}
Also used : OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Aggregations

OAuth2AuthorizationCode (org.springframework.security.oauth2.core.OAuth2AuthorizationCode)17 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)14 RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)13 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)12 Test (org.junit.Test)9 Authentication (org.springframework.security.core.Authentication)9 Principal (java.security.Principal)7 Instant (java.time.Instant)6 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)5 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)5 Map (java.util.Map)4 Set (java.util.Set)4 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)4 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)4 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)4 JwtEncodingContext (org.springframework.security.oauth2.server.authorization.JwtEncodingContext)4 OAuth2AuthorizationConsent (org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent)4 OAuth2TokenContext (org.springframework.security.oauth2.server.authorization.OAuth2TokenContext)4 ChronoUnit (java.time.temporal.ChronoUnit)3