Search in sources :

Example 1 with SignatureAlgorithm

use of org.springframework.security.oauth2.jose.jws.SignatureAlgorithm in project spring-security by spring-projects.

the class JwtDecoderProviderConfigurationUtilsTests method getSignatureAlgorithmsWhenAlgorithmThenParses.

// gh-9651
@Test
public void getSignatureAlgorithmsWhenAlgorithmThenParses() throws Exception {
    JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
    RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(new Algorithm(JwsAlgorithms.RS256)).build();
    given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
    Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
    assertThat(algorithms).containsOnly(SignatureAlgorithm.RS256);
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) RSAKey(com.nimbusds.jose.jwk.RSAKey) SecurityContext(com.nimbusds.jose.proc.SecurityContext) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) Algorithm(com.nimbusds.jose.Algorithm) Test(org.junit.jupiter.api.Test)

Example 2 with SignatureAlgorithm

use of org.springframework.security.oauth2.jose.jws.SignatureAlgorithm in project spring-security by spring-projects.

the class JwtDecoderProviderConfigurationUtilsTests method getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses.

@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses() throws Exception {
    JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
    RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(JWSAlgorithm.RS384).build();
    given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
    Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
    assertThat(algorithms).containsOnly(SignatureAlgorithm.RS384);
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) RSAKey(com.nimbusds.jose.jwk.RSAKey) SecurityContext(com.nimbusds.jose.proc.SecurityContext) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) Test(org.junit.jupiter.api.Test)

Example 3 with SignatureAlgorithm

use of org.springframework.security.oauth2.jose.jws.SignatureAlgorithm in project spring-security by spring-projects.

the class OidcIdTokenDecoderFactory method buildDecoder.

private NimbusJwtDecoder buildDecoder(ClientRegistration clientRegistration) {
    JwsAlgorithm jwsAlgorithm = this.jwsAlgorithmResolver.apply(clientRegistration);
    if (jwsAlgorithm != null && SignatureAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 6. If the ID Token is received via direct communication between the Client
        // and the Token Endpoint (which it is in this flow),
        // the TLS server validation MAY be used to validate the issuer in place of
        // checking the token signature.
        // The Client MUST validate the signature of all other ID Tokens according to
        // JWS [JWS]
        // using the algorithm specified in the JWT alg Header Parameter.
        // The Client MUST use the keys provided by the Issuer.
        // 
        // 7. The alg value SHOULD be the default of RS256 or the algorithm sent by
        // the Client
        // in the id_token_signed_response_alg parameter during Registration.
        String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
        if (!StringUtils.hasText(jwkSetUri)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the JwkSet URI.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm).build();
    }
    if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 8. If the JWT alg Header Parameter uses a MAC based algorithm such as
        // HS256, HS384, or HS512,
        // the octets of the UTF-8 representation of the client_secret
        // corresponding to the client_id contained in the aud (audience) Claim
        // are used as the key to validate the signature.
        // For MAC based algorithms, the behavior is unspecified if the aud is
        // multi-valued or
        // if an azp value is present that is different than the aud value.
        String clientSecret = clientRegistration.getClientSecret();
        if (!StringUtils.hasText(clientSecret)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the client secret.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
        return NimbusJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm).build();
    }
    OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'", null);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
Also used : JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) SecretKeySpec(javax.crypto.spec.SecretKeySpec) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 4 with SignatureAlgorithm

use of org.springframework.security.oauth2.jose.jws.SignatureAlgorithm in project spring-security by spring-projects.

the class ReactiveOidcIdTokenDecoderFactory method buildDecoder.

private NimbusReactiveJwtDecoder buildDecoder(ClientRegistration clientRegistration) {
    JwsAlgorithm jwsAlgorithm = this.jwsAlgorithmResolver.apply(clientRegistration);
    if (jwsAlgorithm != null && SignatureAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 6. If the ID Token is received via direct communication between the Client
        // and the Token Endpoint (which it is in this flow),
        // the TLS server validation MAY be used to validate the issuer in place of
        // checking the token signature.
        // The Client MUST validate the signature of all other ID Tokens according to
        // JWS [JWS]
        // using the algorithm specified in the JWT alg Header Parameter.
        // The Client MUST use the keys provided by the Issuer.
        // 
        // 7. The alg value SHOULD be the default of RS256 or the algorithm sent by
        // the Client
        // in the id_token_signed_response_alg parameter during Registration.
        String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
        if (!StringUtils.hasText(jwkSetUri)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the JwkSet URI.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm).build();
    }
    if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 8. If the JWT alg Header Parameter uses a MAC based algorithm such as
        // HS256, HS384, or HS512,
        // the octets of the UTF-8 representation of the client_secret
        // corresponding to the client_id contained in the aud (audience) Claim
        // are used as the key to validate the signature.
        // For MAC based algorithms, the behavior is unspecified if the aud is
        // multi-valued or
        // if an azp value is present that is different than the aud value.
        String clientSecret = clientRegistration.getClientSecret();
        if (!StringUtils.hasText(clientSecret)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the client secret.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
        return NimbusReactiveJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm).build();
    }
    OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'", null);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
Also used : JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) SecretKeySpec(javax.crypto.spec.SecretKeySpec) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 5 with SignatureAlgorithm

use of org.springframework.security.oauth2.jose.jws.SignatureAlgorithm in project spring-security by spring-projects.

the class NimbusJwtDecoderTests method withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes.

// gh-8730
@Test
public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception {
    RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY;
    RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY;
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("JWS")).build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet);
    // @formatter:off
    NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey).signatureAlgorithm(SignatureAlgorithm.RS256).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
    // @formatter:on
    assertThat(decoder.decode(signedJwt.serialize()).hasClaim(JwtClaimNames.EXP)).isNotNull();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) Arrays(java.util.Arrays) EncodedKeySpec(java.security.spec.EncodedKeySpec) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) BeforeAll(org.junit.jupiter.api.BeforeAll) BDDMockito.given(org.mockito.BDDMockito.given) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) ParseException(java.text.ParseException) RestClientException(org.springframework.web.client.RestClientException) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) MediaType(org.springframework.http.MediaType) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Instant(java.time.Instant) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) List(java.util.List) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) JWSSigner(com.nimbusds.jose.JWSSigner) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) SecretKey(javax.crypto.SecretKey) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) Cache(org.springframework.cache.Cache) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Callable(java.util.concurrent.Callable) JWTProcessor(com.nimbusds.jwt.proc.JWTProcessor) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) BadJWTException(com.nimbusds.jwt.proc.BadJWTException) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) MACSigner(com.nimbusds.jose.crypto.MACSigner) Converter(org.springframework.core.convert.converter.Converter) RequestEntity(org.springframework.http.RequestEntity) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RestOperations(org.springframework.web.client.RestOperations) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) DefaultJOSEObjectTypeVerifier(com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Aggregations

SignatureAlgorithm (org.springframework.security.oauth2.jose.jws.SignatureAlgorithm)7 SecurityContext (com.nimbusds.jose.proc.SecurityContext)4 Test (org.junit.jupiter.api.Test)4 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 JWKSelector (com.nimbusds.jose.jwk.JWKSelector)3 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)3 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)3 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)2 JwsAlgorithm (org.springframework.security.oauth2.jose.jws.JwsAlgorithm)2 Algorithm (com.nimbusds.jose.Algorithm)1 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)1 JWSHeader (com.nimbusds.jose.JWSHeader)1 JWSSigner (com.nimbusds.jose.JWSSigner)1 MACSigner (com.nimbusds.jose.crypto.MACSigner)1 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)1 ECKey (com.nimbusds.jose.jwk.ECKey)1 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)1 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)1