Search in sources :

Example 21 with OAuth2AuthorizationException

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

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    // Build the authorization code grant request for the token endpoint
    AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
    URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
    URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
    // Set the credentials to authenticate the client at the token endpoint
    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
    ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
    com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
    if (!tokenResponse.indicatesSuccess()) {
        TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
        ErrorObject errorObject = tokenErrorResponse.getErrorObject();
        throw new OAuth2AuthorizationException(getOAuthError(errorObject));
    }
    AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
    String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }
    long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
    // As per spec, in section 5.1 Successful Access Token Response
    // https://tools.ietf.org/html/rfc6749#section-5.1
    // If AccessTokenResponse.scope is empty, then default to the scope
    // originally requested by the client in the Authorization Request
    Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
    String refreshToken = null;
    if (accessTokenResponse.getTokens().getRefreshToken() != null) {
        refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
    }
    Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
    // @formatter:off
    return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
Also used : URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) LinkedHashMap(java.util.LinkedHashMap) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Example 22 with OAuth2AuthorizationException

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

the class OAuth2AuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
    OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
    if (authorizationResponse.statusError()) {
        throw new OAuth2AuthorizationException(authorizationResponse.getError());
    }
    OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
    if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange()));
    OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters());
    authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 23 with OAuth2AuthorizationException

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

the class DefaultReactiveOAuth2AuthorizedClientManagerTests method authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient.

@SuppressWarnings("unchecked")
@Test
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(Mono.just(this.clientRegistration));
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).build();
    OAuth2AuthorizationException exception = new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.error(exception));
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()).isEqualTo(exception);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isNull();
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
    verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) Test(org.junit.jupiter.api.Test)

Example 24 with OAuth2AuthorizationException

use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.

the class UaaAuthorizationHeaderUtil method getAuthorizationHeader.

public String getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Optional<OAuth2AuthorizedClient> client = Optional.ofNullable(clientRegistrationService.loadAuthorizedClient(CLIENT_REGISTRATION_ID, authentication.getName()));
    if (!client.isPresent() || client.get().getAccessToken() == null) {
        log.info("AccessToken not found, refreshing automatically");
        client = refreshAuthorizedClient(authentication);
    } else if (isExpired(client.get().getAccessToken())) {
        log.info("AccessToken expired, refreshing automatically");
        client = refreshAuthorizedClient(authentication);
    }
    return client.map(OAuth2AuthorizedClient::getAccessToken).map(this::toAuthorizationHeaderValue).orElseThrow(() -> new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, "Unable to get access token for user", null)));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Authentication(org.springframework.security.core.Authentication) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

Example 25 with OAuth2AuthorizationException

use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.

the class AuthorizationHeaderUtil method getAuthorizationHeader.

public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    String name = oauthToken.getName();
    String registrationId = oauthToken.getAuthorizedClientRegistrationId();
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(registrationId, name);
    if (null == client) {
        throw new OAuth2AuthorizationException(new OAuth2Error("access_denied", "The token is expired", null));
    }
    OAuth2AccessToken accessToken = client.getAccessToken();
    if (accessToken != null) {
        String tokenType = accessToken.getTokenType().getValue();
        String accessTokenValue = accessToken.getTokenValue();
        if (isExpired(accessToken)) {
            log.info("AccessToken expired, refreshing automatically");
            accessTokenValue = refreshToken(client, oauthToken);
            if (null == accessTokenValue) {
                SecurityContextHolder.getContext().setAuthentication(null);
                throw new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, "The token is expired", null));
            }
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessTokenValue);
        return Optional.of(authorizationHeaderValue);
    }
    return Optional.empty();
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

Aggregations

OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)24 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)19 Test (org.junit.jupiter.api.Test)10 Authentication (org.springframework.security.core.Authentication)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)6 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)5 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)5 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)4 URI (java.net.URI)3 Instant (java.time.Instant)3 Collections (java.util.Collections)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)3 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)3 OAuth2ErrorCodes (org.springframework.security.oauth2.core.OAuth2ErrorCodes)3 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)3 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)3