Search in sources :

Example 31 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 32 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)

Example 33 with OAuth2Error

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

the class JwtTimestampValidatorTests method validateWhenJwtIsTooEarlyThenErrorMessageIndicatesNotBeforeTime.

@Test
public void validateWhenJwtIsTooEarlyThenErrorMessageIndicatesNotBeforeTime() {
    Instant oneHourFromNow = Instant.now().plusSeconds(3600);
    Jwt jwt = TestJwts.jwt().notBefore(oneHourFromNow).build();
    JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
    Collection<OAuth2Error> details = jwtValidator.validate(jwt).getErrors();
    // @formatter:off
    Collection<String> messages = details.stream().map(OAuth2Error::getDescription).collect(Collectors.toList());
    // @formatter:on
    assertThat(messages).contains("Jwt used before " + oneHourFromNow);
    assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN));
}
Also used : Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Example 34 with OAuth2Error

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

the class NimbusJwtDecoderTests method decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage.

@Test
public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() {
    OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
    OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
    given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure));
    this.jwtDecoder.setJwtValidator(jwtValidator);
    // @formatter:off
    assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
// @formatter:on
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Example 35 with OAuth2Error

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

the class NimbusReactiveJwtDecoderTests method decodeWhenReadingErrorPickTheFirstErrorMessage.

@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
    OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
    this.decoder.setJwtValidator(jwtValidator);
    OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
    OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
    OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
    OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
    given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
    // @formatter:off
    assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()).withMessageContaining("mock-description");
// @formatter:on
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)134 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)58 Test (org.junit.jupiter.api.Test)53 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)25 Authentication (org.springframework.security.core.Authentication)23 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)14 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 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)9 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8