Search in sources :

Example 61 with OAuth2Error

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

the class NimbusJwtDecoderJwkSupportTests method decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage.

@Test
public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() throws Exception {
    try (MockWebServer server = new MockWebServer()) {
        server.enqueue(new MockResponse().setBody(JWK_SET));
        String jwkSetUrl = server.url("/.well-known/jwks.json").toString();
        NimbusJwtDecoderJwkSupport decoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl);
        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));
        decoder.setJwtValidator(jwtValidator);
        // @formatter:off
        assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
    // @formatter:on
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Example 62 with OAuth2Error

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

the class JwtTimestampValidatorTests method validateWhenJwtIsExpiredThenErrorMessageIndicatesExpirationTime.

@Test
public void validateWhenJwtIsExpiredThenErrorMessageIndicatesExpirationTime() {
    Instant oneHourAgo = Instant.now().minusSeconds(3600);
    Jwt jwt = TestJwts.jwt().expiresAt(oneHourAgo).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 expired at " + oneHourAgo);
    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 63 with OAuth2Error

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

the class JwtTimestampValidatorTests method validateWhenConfiguredWithClockSkewThenValidatesUsingThatSkew.

@Test
public void validateWhenConfiguredWithClockSkewThenValidatesUsingThatSkew() {
    Duration oneDayOff = Duration.ofDays(1);
    JwtTimestampValidator jwtValidator = new JwtTimestampValidator(oneDayOff);
    Instant now = Instant.now();
    Instant almostOneDayAgo = now.minus(oneDayOff).plusSeconds(10);
    Instant almostOneDayFromNow = now.plus(oneDayOff).minusSeconds(10);
    Instant justOverOneDayAgo = now.minus(oneDayOff).minusSeconds(10);
    Instant justOverOneDayFromNow = now.plus(oneDayOff).plusSeconds(10);
    Jwt jwt = TestJwts.jwt().expiresAt(almostOneDayAgo).notBefore(almostOneDayFromNow).build();
    assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
    jwt = TestJwts.jwt().expiresAt(justOverOneDayAgo).build();
    OAuth2TokenValidatorResult result = jwtValidator.validate(jwt);
    // @formatter:off
    Collection<String> messages = result.getErrors().stream().map(OAuth2Error::getDescription).collect(Collectors.toList());
    // @formatter:on
    assertThat(result.hasErrors()).isTrue();
    assertThat(messages).contains("Jwt expired at " + justOverOneDayAgo);
    jwt = TestJwts.jwt().notBefore(justOverOneDayFromNow).build();
    result = jwtValidator.validate(jwt);
    // @formatter:off
    messages = result.getErrors().stream().map(OAuth2Error::getDescription).collect(Collectors.toList());
    // @formatter:on
    assertThat(result.hasErrors()).isTrue();
    assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN);
    assertThat(messages).contains("Jwt used before " + justOverOneDayFromNow);
}
Also used : Instant(java.time.Instant) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Duration(java.time.Duration) Test(org.junit.jupiter.api.Test)

Example 64 with OAuth2Error

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

the class JwtTimestampValidator method validate.

@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    Assert.notNull(jwt, "jwt cannot be null");
    Instant expiry = jwt.getExpiresAt();
    if (expiry != null) {
        if (Instant.now(this.clock).minus(this.clockSkew).isAfter(expiry)) {
            OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt()));
            return OAuth2TokenValidatorResult.failure(oAuth2Error);
        }
    }
    Instant notBefore = jwt.getNotBefore();
    if (notBefore != null) {
        if (Instant.now(this.clock).plus(this.clockSkew).isBefore(notBefore)) {
            OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore()));
            return OAuth2TokenValidatorResult.failure(oAuth2Error);
        }
    }
    return OAuth2TokenValidatorResult.success();
}
Also used : Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error)

Example 65 with OAuth2Error

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

the class NimbusReactiveJwtDecoder method validateJwt.

private Jwt validateJwt(Jwt jwt) {
    OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt);
    if (result.hasErrors()) {
        Collection<OAuth2Error> errors = result.getErrors();
        String validationErrorString = getJwtValidationExceptionMessage(errors);
        throw new JwtValidationException(validationErrorString, errors);
    }
    return jwt;
}
Also used : OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error)

Aggregations

OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)80 Test (org.junit.jupiter.api.Test)52 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)30 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)19 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)16 Authentication (org.springframework.security.core.Authentication)12 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)12 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)11 Map (java.util.Map)10 Jwt (org.springframework.security.oauth2.jwt.Jwt)10 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)9 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 Instant (java.time.Instant)8 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 BDDMockito.given (org.mockito.BDDMockito.given)8 Mockito.mock (org.mockito.Mockito.mock)8 Mockito.verify (org.mockito.Mockito.verify)8 Mono (reactor.core.publisher.Mono)8 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)7