Search in sources :

Example 46 with OAuth2AuthenticationException

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

the class OidcAuthorizationCodeReactiveAuthenticationManager method authenticate.

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
    return Mono.defer(() -> {
        OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
        // value.
        if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
            // and let OAuth2LoginReactiveAuthenticationManager handle it instead
            return Mono.empty();
        }
        OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
        OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
        if (authorizationResponse.statusError()) {
            return Mono.error(new OAuth2AuthenticationException(authorizationResponse.getError(), authorizationResponse.getError().toString()));
        }
        if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
            return Mono.error(new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()));
        }
        OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange());
        return this.accessTokenResponseClient.getTokenResponse(authzRequest).flatMap((accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse)).onErrorMap(OAuth2AuthorizationException.class, (e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e)).onErrorMap(JwtException.class, (e) -> {
            OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(), null);
            return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), e);
        });
    });
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) MessageDigest(java.security.MessageDigest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) Collection(java.util.Collection) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwtException(org.springframework.security.oauth2.jwt.JwtException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Assert(org.springframework.util.Assert) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 47 with OAuth2AuthenticationException

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

the class OidcAuthorizationCodeReactiveAuthenticationManager method authenticationResult.

private Mono<OAuth2LoginAuthenticationToken> authenticationResult(OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OAuth2AccessTokenResponse accessTokenResponse) {
    OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
    ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
    Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
    if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
        OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Missing (required) ID Token in Token Response for Client Registration: " + clientRegistration.getRegistrationId(), null);
        return Mono.error(new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString()));
    }
    // @formatter:off
    return createOidcToken(clientRegistration, accessTokenResponse).doOnNext((idToken) -> validateNonce(authorizationCodeAuthentication, idToken)).map((idToken) -> new OidcUserRequest(clientRegistration, accessToken, idToken, additionalParameters)).flatMap(this.userService::loadUser).map((oauth2User) -> {
        Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
        return new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, accessTokenResponse.getRefreshToken());
    });
// @formatter:on
}
Also used : OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) MessageDigest(java.security.MessageDigest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) Collection(java.util.Collection) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwtException(org.springframework.security.oauth2.jwt.JwtException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Assert(org.springframework.util.Assert) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 48 with OAuth2AuthenticationException

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

the class OAuth2AuthenticationExceptionMixinTests method deserializeWhenMixinRegisteredThenDeserializes.

@Test
public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception {
    OAuth2AuthenticationException expected = new OAuth2AuthenticationException(new OAuth2Error("[authorization_request_not_found]", "Authorization Request Not Found", "/foo/bar"), "Authorization Request Not Found");
    OAuth2AuthenticationException exception = this.mapper.readValue(asJson(expected), OAuth2AuthenticationException.class);
    assertThat(exception).isNotNull();
    assertThat(exception.getCause()).isNull();
    assertThat(exception.getMessage()).isEqualTo(expected.getMessage());
    OAuth2Error oauth2Error = exception.getError();
    assertThat(oauth2Error).isNotNull();
    assertThat(oauth2Error.getErrorCode()).isEqualTo(expected.getError().getErrorCode());
    assertThat(oauth2Error.getDescription()).isEqualTo(expected.getError().getDescription());
    assertThat(oauth2Error.getUri()).isEqualTo(expected.getError().getUri());
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Example 49 with OAuth2AuthenticationException

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

the class BearerTokenAuthenticationFilterTests method doFilterWhenAuthenticationFailsWithDefaultHandlerThenPropagatesError.

@Test
public void doFilterWhenAuthenticationFailsWithDefaultHandlerThenPropagatesError() throws ServletException, IOException {
    BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, "description", "uri");
    OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
    given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
    given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
    BearerTokenAuthenticationFilter filter = addMocks(new BearerTokenAuthenticationFilter(this.authenticationManager));
    filter.doFilter(this.request, this.response, this.filterChain);
    verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
Also used : BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 50 with OAuth2AuthenticationException

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

the class BearerTokenAuthenticationFilterTests method doFilterWhenMalformedBearerTokenThenPropagatesError.

@Test
public void doFilterWhenMalformedBearerTokenThenPropagatesError() throws ServletException, IOException {
    BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, "description", "uri");
    OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
    given(this.bearerTokenResolver.resolve(this.request)).willThrow(exception);
    dontAuthenticate();
    verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
Also used : BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)52 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)31 Test (org.junit.jupiter.api.Test)27 BearerTokenError (org.springframework.security.oauth2.server.resource.BearerTokenError)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)7 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)7 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)7 Map (java.util.Map)6 Authentication (org.springframework.security.core.Authentication)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)6 Mono (reactor.core.publisher.Mono)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Base64 (java.util.Base64)5