Search in sources :

Example 1 with JwtException

use of org.springframework.security.oauth2.jwt.JwtException in project spring-security by spring-projects.

the class JwtReactiveAuthenticationManagerTests method authenticateWhenDecoderFailsGenericallyThenThrowsGenericException.

// gh-7785
@Test
public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() {
    BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
    given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set"));
    // @formatter:off
    assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.manager.authenticate(token).block()).isNotInstanceOf(OAuth2AuthenticationException.class);
// @formatter:on
}
Also used : JwtException(org.springframework.security.oauth2.jwt.JwtException) BadJwtException(org.springframework.security.oauth2.jwt.BadJwtException) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 2 with JwtException

use of org.springframework.security.oauth2.jwt.JwtException in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenIdTokenValidationErrorThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenIdTokenValidationErrorThenThrowOAuth2AuthenticationException() {
    JwtDecoder jwtDecoder = mock(JwtDecoder.class);
    given(jwtDecoder.decode(anyString())).willThrow(new JwtException("ID Token Validation Error"));
    this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange))).withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
Also used : JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) JwtException(org.springframework.security.oauth2.jwt.JwtException) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 3 with JwtException

use of org.springframework.security.oauth2.jwt.JwtException in project spring-security by spring-projects.

the class NimbusJwtDecoder method createJwt.

private Jwt createJwt(String token, JWT parsedJwt) {
    try {
        // Verify the signature
        JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
        Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
        Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
        // @formatter:off
        return Jwt.withTokenValue(token).headers((h) -> h.putAll(headers)).claims((c) -> c.putAll(claims)).build();
    // @formatter:on
    } catch (RemoteKeySourceException ex) {
        this.logger.trace("Failed to retrieve JWK set", ex);
        if (ex.getCause() instanceof ParseException) {
            throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"), ex);
        }
        throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    } catch (JOSEException ex) {
        this.logger.trace("Failed to process JWT", ex);
        throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    } catch (Exception ex) {
        this.logger.trace("Failed to process JWT", ex);
        if (ex.getCause() instanceof ParseException) {
            throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"), ex);
        }
        throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    }
}
Also used : Arrays(java.util.Arrays) URL(java.net.URL) JOSEException(com.nimbusds.jose.JOSEException) JWKSet(com.nimbusds.jose.jwk.JWKSet) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) JWTParser(com.nimbusds.jwt.JWTParser) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) JWKSetCache(com.nimbusds.jose.jwk.source.JWKSetCache) PlainJWT(com.nimbusds.jwt.PlainJWT) RSAPublicKey(java.security.interfaces.RSAPublicKey) Map(java.util.Map) JWT(com.nimbusds.jwt.JWT) ParseException(java.text.ParseException) RestTemplate(org.springframework.web.client.RestTemplate) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) HttpHeaders(org.springframework.http.HttpHeaders) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) SecretKey(javax.crypto.SecretKey) LogFactory(org.apache.commons.logging.LogFactory) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) SecurityContext(com.nimbusds.jose.proc.SecurityContext) Resource(com.nimbusds.jose.util.Resource) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) Cache(org.springframework.cache.Cache) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWTProcessor(com.nimbusds.jwt.proc.JWTProcessor) RemoteJWKSet(com.nimbusds.jose.jwk.source.RemoteJWKSet) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) Converter(org.springframework.core.convert.converter.Converter) RequestEntity(org.springframework.http.RequestEntity) ConfigurableJWTProcessor(com.nimbusds.jwt.proc.ConfigurableJWTProcessor) MalformedURLException(java.net.MalformedURLException) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) RestOperations(org.springframework.web.client.RestOperations) SingleKeyJWSKeySelector(com.nimbusds.jose.proc.SingleKeyJWSKeySelector) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) Consumer(java.util.function.Consumer) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Log(org.apache.commons.logging.Log) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JOSEException(com.nimbusds.jose.JOSEException) ParseException(java.text.ParseException) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with JwtException

use of org.springframework.security.oauth2.jwt.JwtException in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenIdTokenValidationErrorThenOAuth2AuthenticationException.

@Test
public void authenticateWhenIdTokenValidationErrorThenOAuth2AuthenticationException() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).build();
    // @formatter:on
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.manager.authenticate(loginToken()).block()).withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) JwtException(org.springframework.security.oauth2.jwt.JwtException) Test(org.junit.jupiter.api.Test)

Example 5 with JwtException

use of org.springframework.security.oauth2.jwt.JwtException in project spring-security by spring-projects.

the class JwtAuthenticationProviderTests method authenticateWhenDecoderFailsGenericallyThenThrowsGenericException.

// gh-7785
@Test
public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() {
    BearerTokenAuthenticationToken token = this.authentication();
    given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set"));
    // @formatter:off
    assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.provider.authenticate(token)).isNotInstanceOf(OAuth2AuthenticationException.class);
// @formatter:on
}
Also used : JwtException(org.springframework.security.oauth2.jwt.JwtException) BadJwtException(org.springframework.security.oauth2.jwt.BadJwtException) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)4 JwtException (org.springframework.security.oauth2.jwt.JwtException)4 JOSEException (com.nimbusds.jose.JOSEException)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RemoteKeySourceException (com.nimbusds.jose.RemoteKeySourceException)1 JWKSet (com.nimbusds.jose.jwk.JWKSet)1 JWKSetCache (com.nimbusds.jose.jwk.source.JWKSetCache)1 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)1 RemoteJWKSet (com.nimbusds.jose.jwk.source.RemoteJWKSet)1 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)1 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)1 SecurityContext (com.nimbusds.jose.proc.SecurityContext)1 SingleKeyJWSKeySelector (com.nimbusds.jose.proc.SingleKeyJWSKeySelector)1 Resource (com.nimbusds.jose.util.Resource)1 ResourceRetriever (com.nimbusds.jose.util.ResourceRetriever)1 JWT (com.nimbusds.jwt.JWT)1 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 JWTParser (com.nimbusds.jwt.JWTParser)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 ConfigurableJWTProcessor (com.nimbusds.jwt.proc.ConfigurableJWTProcessor)1