Search in sources :

Example 1 with NimbusJwtDecoder

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized() throws Exception {
    RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
    given(this.jwkResolver.apply(any())).willReturn(rsaJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

Example 2 with NimbusJwtDecoder

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized() {
    OctetSequenceKey secretJwk = TestJwks.DEFAULT_SECRET_JWK;
    given(this.jwkResolver.apply(any())).willReturn(secretJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) OctetSequenceKey(com.nimbusds.jose.jwk.OctetSequenceKey) Test(org.junit.jupiter.api.Test)

Example 3 with NimbusJwtDecoder

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenClientKeyChangesThenNewKeyUsed.

// gh-9814
@Test
public void convertWhenClientKeyChangesThenNewKeyUsed() throws Exception {
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    RSAKey rsaJwk1 = TestJwks.DEFAULT_RSA_JWK;
    given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk1);
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk1.toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws);
    RSAKey rsaJwk2 = generateRsaJwk();
    given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk2);
    parameters = this.converter.convert(clientCredentialsGrantRequest);
    encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk2.toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws);
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Test(org.junit.jupiter.api.Test)

Example 4 with NimbusJwtDecoder

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

the class NimbusJwtDecoderTests method withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType.

// gh-8730
@Test
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
    RestOperations restOperations = mock(RestOperations.class);
    given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
    // @formatter:off
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
    assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("An error occurred while attempting to decode the Jwt: " + "Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
Also used : 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) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test)

Example 5 with NimbusJwtDecoder

use of org.springframework.security.oauth2.jwt.NimbusJwtDecoder in project midpoint by Evolveum.

the class OidcResourceServerModuleWebSecurityConfiguration method buildInternal.

private static OidcResourceServerModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence) {
    OidcResourceServerModuleWebSecurityConfiguration configuration = new OidcResourceServerModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    OidcResourceServerAuthenticationModuleType resourceServer = modelType.getResourceServer();
    if (resourceServer.getTrustingAsymmetricCertificate() != null || resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
        NimbusJwtDecoder.PublicKeyJwtDecoderBuilder builder;
        if (resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
            builder = initializePublicKeyDecoderFromKeyStore(resourceServer.getKeyStoreTrustingAsymmetricKey());
        } else {
            builder = initializePublicKeyDecoderFromCertificate(resourceServer.getTrustingAsymmetricCertificate());
        }
        if (resourceServer.getTrustedAlgorithm() != null) {
            builder.signatureAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm()));
        }
        configuration.decoder = builder.build();
    } else if (resourceServer.getSingleSymmetricKey() != null) {
        try {
            byte[] key;
            String clearValue = protector.decryptString(resourceServer.getSingleSymmetricKey());
            if (Base64.isBase64(clearValue)) {
                boolean isBase64Url = clearValue.contains("-") || clearValue.contains("_");
                key = Base64Utility.decode(clearValue, isBase64Url);
            } else {
                key = protector.decryptString(resourceServer.getSingleSymmetricKey()).getBytes();
            }
            String algorithm = MacAlgorithm.HS256.getName();
            if (resourceServer.getTrustedAlgorithm() != null) {
                algorithm = resourceServer.getTrustedAlgorithm();
            }
            NimbusJwtDecoder.SecretKeyJwtDecoderBuilder builder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(key, algorithm));
            builder.macAlgorithm(MacAlgorithm.from(algorithm));
            configuration.decoder = builder.build();
        } catch (EncryptionException e) {
            throw new OAuth2AuthenticationException(new OAuth2Error("missing_key"), "Unable get single symmetric key", e);
        } catch (Base64Exception e) {
            e.printStackTrace();
        }
    } else if (resourceServer.getJwkSetUri() != null) {
        if (resourceServer.getTrustedAlgorithm() != null) {
            configuration.decoder = NimbusJwtDecoder.withJwkSetUri(resourceServer.getJwkSetUri()).jwsAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm())).build();
        } else {
            try {
                JWSKeySelector<SecurityContext> jwsKeySelector = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(resourceServer.getJwkSetUri()));
                DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
                jwtProcessor.setJWSKeySelector(jwsKeySelector);
                configuration.decoder = new NimbusJwtDecoder(jwtProcessor);
            } catch (KeySourceException | MalformedURLException e) {
                e.printStackTrace();
            }
        }
    } else if (resourceServer.getIssuerUri() != null) {
        configuration.decoder = JwtDecoders.fromIssuerLocation(resourceServer.getIssuerUri());
    }
    return configuration;
}
Also used : MalformedURLException(java.net.MalformedURLException) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) URL(java.net.URL) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Base64Exception(org.apache.cxf.common.util.Base64Exception) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SecurityContext(com.nimbusds.jose.proc.SecurityContext) KeySourceException(com.nimbusds.jose.KeySourceException)

Aggregations

Test (org.junit.jupiter.api.Test)8 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)5 SignedJWT (com.nimbusds.jwt.SignedJWT)5 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)5 SecurityContext (com.nimbusds.jose.proc.SecurityContext)4 DefaultJWTProcessor (com.nimbusds.jwt.proc.DefaultJWTProcessor)4 SecretKey (javax.crypto.SecretKey)4 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)4 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 JWSHeader (com.nimbusds.jose.JWSHeader)3 JWSSigner (com.nimbusds.jose.JWSSigner)3 MACSigner (com.nimbusds.jose.crypto.MACSigner)3 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)3 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)3 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)3 DefaultJOSEObjectTypeVerifier (com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier)3 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)3 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)3 BadJWTException (com.nimbusds.jwt.proc.BadJWTException)3