Search in sources :

Example 16 with OAuth2Error

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

the class OAuth2AccessTokenResponseBodyExtractor method oauth2AccessTokenResponse.

private static Mono<AccessTokenResponse> oauth2AccessTokenResponse(TokenResponse tokenResponse) {
    if (tokenResponse.indicatesSuccess()) {
        return Mono.just(tokenResponse).cast(AccessTokenResponse.class);
    }
    TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
    ErrorObject errorObject = tokenErrorResponse.getErrorObject();
    OAuth2Error oauth2Error = getOAuth2Error(errorObject);
    return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error)

Example 17 with OAuth2Error

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

the class BearerTokenServerAuthenticationEntryPoint method createParameters.

private Map<String, String> createParameters(AuthenticationException authException) {
    Map<String, String> parameters = new LinkedHashMap<>();
    if (this.realmName != null) {
        parameters.put("realm", this.realmName);
    }
    if (authException instanceof OAuth2AuthenticationException) {
        OAuth2Error error = ((OAuth2AuthenticationException) authException).getError();
        parameters.put("error", error.getErrorCode());
        if (StringUtils.hasText(error.getDescription())) {
            parameters.put("error_description", error.getDescription());
        }
        if (StringUtils.hasText(error.getUri())) {
            parameters.put("error_uri", error.getUri());
        }
        if (error instanceof BearerTokenError) {
            BearerTokenError bearerTokenError = (BearerTokenError) error;
            if (StringUtils.hasText(bearerTokenError.getScope())) {
                parameters.put("scope", bearerTokenError.getScope());
            }
        }
    }
    return parameters;
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) LinkedHashMap(java.util.LinkedHashMap)

Example 18 with OAuth2Error

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

the class BearerTokenServerAuthenticationEntryPointTests method commenceWhenBearerTokenThenErrorInformation.

@Test
public void commenceWhenBearerTokenThenErrorInformation() {
    OAuth2Error oauthError = new BearerTokenError(OAuth2ErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, "Oops", "https://example.com");
    OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
    this.entryPoint.commence(this.exchange, exception).block();
    assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo("Bearer error=\"invalid_request\", error_description=\"Oops\", error_uri=\"https://example.com\"");
    assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Example 19 with OAuth2Error

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

the class OAuth2LoginTests method oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin.

// gh-6484
@Test
public void oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    // @formatter:off
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    // @formatter:on
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken authenticationToken = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()).tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()).additionalParameters(additionalParameters).build();
    // @formatter:on
    ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
    given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
    OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
    given(jwtDecoderFactory.createDecoder(any())).willReturn((token) -> Mono.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", "/login?error");
// @formatter:on
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) HashMap(java.util.HashMap) 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) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 20 with OAuth2Error

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

the class OAuth2ResourceServerSpecTests method getWhenUsingCustomAuthenticationManagerInLambdaThenUsesItAccordingly.

@Test
public void getWhenUsingCustomAuthenticationManagerInLambdaThenUsesItAccordingly() {
    this.spring.register(CustomAuthenticationManagerInLambdaConfig.class).autowire();
    ReactiveAuthenticationManager authenticationManager = this.spring.getContext().getBean(ReactiveAuthenticationManager.class);
    given(authenticationManager.authenticate(any(Authentication.class))).willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
    // @formatter:off
    this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus().isUnauthorized().expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
// @formatter:on
}
Also used : JwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) RSAPublicKey(java.security.interfaces.RSAPublicKey) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) MockWebServer(okhttp3.mockwebserver.MockWebServer) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) BigInteger(java.math.BigInteger) ReactiveAuthenticationManagerResolver(org.springframework.security.authentication.ReactiveAuthenticationManagerResolver) Jwt(org.springframework.security.oauth2.jwt.Jwt) HttpHeaders(org.apache.http.HttpHeaders) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) PostMapping(org.springframework.web.bind.annotation.PostMapping) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) PreDestroy(jakarta.annotation.PreDestroy) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) Stream(java.util.stream.Stream) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) MockResponse(okhttp3.mockwebserver.MockResponse) Authentication(org.springframework.security.core.Authentication) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ReactiveJwtAuthenticationConverterAdapter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) ReactiveJwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DispatcherHandler(org.springframework.web.reactive.DispatcherHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Value(org.springframework.beans.factory.annotation.Value) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) Dispatcher(okhttp3.mockwebserver.Dispatcher) BeanCreationException(org.springframework.beans.factory.BeanCreationException) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) GetMapping(org.springframework.web.bind.annotation.GetMapping) NoUniqueBeanDefinitionException(org.springframework.beans.factory.NoUniqueBeanDefinitionException) Converter(org.springframework.core.convert.converter.Converter) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) ApplicationContext(org.springframework.context.ApplicationContext) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) HttpStatusServerEntryPoint(org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint) SpringTestContext(org.springframework.security.config.test.SpringTestContext) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) HttpStatusServerAccessDeniedHandler(org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Bean(org.springframework.context.annotation.Bean) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) Authentication(org.springframework.security.core.Authentication) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)129 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)54 Test (org.junit.jupiter.api.Test)53 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)25 Authentication (org.springframework.security.core.Authentication)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)17 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)16 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)16 Jwt (org.springframework.security.oauth2.jwt.Jwt)15 Instant (java.time.Instant)13 Map (java.util.Map)13 FilterChain (javax.servlet.FilterChain)12 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 OAuth2TokenValidatorResult (org.springframework.security.oauth2.core.OAuth2TokenValidatorResult)10 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)9 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 BDDMockito.given (org.mockito.BDDMockito.given)8