Search in sources :

Example 1 with OAuth2AuthorizationException

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

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with OAuth2AuthorizationException

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

the class OAuth2AuthorizationCodeReactiveAuthenticationManager method authenticate.

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
    return Mono.defer(() -> {
        OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
        OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange().getAuthorizationResponse();
        if (authorizationResponse.statusError()) {
            return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError()));
        }
        OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange().getAuthorizationRequest();
        if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
            return Mono.error(new OAuth2AuthorizationException(oauth2Error));
        }
        OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(token.getClientRegistration(), token.getAuthorizationExchange());
        return this.accessTokenResponseClient.getTokenResponse(authzRequest).map(onSuccess(token));
    });
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) 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 3 with OAuth2AuthorizationException

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

the class OAuth2LoginAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
        // and let OidcAuthorizationCodeAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
    try {
        authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange()));
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error oauth2Error = ex.getError();
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
    }
    OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken();
    Map<String, Object> additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters();
    OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
    authenticationResult.setDetails(loginAuthenticationToken.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 4 with OAuth2AuthorizationException

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

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

private com.nimbusds.oauth2.sdk.TokenResponse getTokenResponse(AuthorizationGrant authorizationCodeGrant, URI tokenUri, ClientAuthentication clientAuthentication) {
    try {
        // Send the Access Token request
        TokenRequest tokenRequest = new TokenRequest(tokenUri, clientAuthentication, authorizationCodeGrant);
        HTTPRequest httpRequest = tokenRequest.toHTTPRequest();
        httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
        httpRequest.setConnectTimeout(30000);
        httpRequest.setReadTimeout(30000);
        return com.nimbusds.oauth2.sdk.TokenResponse.parse(httpRequest.send());
    } catch (ParseException | IOException ex) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null);
        throw new OAuth2AuthorizationException(oauth2Error, ex);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ParseException(com.nimbusds.oauth2.sdk.ParseException) IOException(java.io.IOException)

Example 5 with OAuth2AuthorizationException

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

the class OAuth2AuthorizationCodeGrantWebFilterTests method filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException.

// gh-8609
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
    MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
    OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
    MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
    DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.filter.filter(exchange, chain).block()).satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)20 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)17 Test (org.junit.jupiter.api.Test)10 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 Authentication (org.springframework.security.core.Authentication)6 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)5 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)4 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)4 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)4 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 OAuth2ErrorCodes (org.springframework.security.oauth2.core.OAuth2ErrorCodes)3 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)3 StringUtils (org.springframework.util.StringUtils)3 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2