Search in sources :

Example 1 with JwsHeader

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

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with JwsHeader

use of org.springframework.security.oauth2.jwt.JwsHeader 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)

Example 3 with JwsHeader

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

the class NimbusJwtDecoderTests method withSecretKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes.

// gh-8730
@Test
public void withSecretKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception {
    SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
    // @formatter:off
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256).type(new JOSEObjectType("JWS")).build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    // @formatter:on
    SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet);
    // @formatter:off
    NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256).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) SecretKey(javax.crypto.SecretKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 4 with JwsHeader

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

the class JwtIssuerReactiveAuthenticationManagerResolverTests method resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager.

@Test
public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception {
    try (MockWebServer server = new MockWebServer()) {
        String issuer = server.url("").toString();
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)));
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET));
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET));
        JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer))));
        jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY));
        JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver(issuer);
        ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block();
        assertThat(authenticationManager).isNotNull();
        BearerTokenAuthenticationToken token = withBearerToken(jws.serialize());
        Authentication authentication = authenticationManager.authenticate(token).block();
        assertThat(authentication).isNotNull();
        assertThat(authentication.isAuthenticated()).isTrue();
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) JSONObject(net.minidev.json.JSONObject) Authentication(org.springframework.security.core.Authentication) MockWebServer(okhttp3.mockwebserver.MockWebServer) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) Payload(com.nimbusds.jose.Payload) JWSObject(com.nimbusds.jose.JWSObject) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 5 with JwsHeader

use of org.springframework.security.oauth2.jwt.JwsHeader in project dhis2-core by dhis2.

the class JwtUtils method encode.

public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException {
    Assert.notNull(headers, "headers cannot be null");
    Assert.notNull(claims, "claims cannot be null");
    JWK jwk = selectJwk(headers);
    if (jwk == null) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
    } else if (!StringUtils.hasText(jwk.getKeyID())) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "The \"kid\" (key ID) from the selected JWK cannot be empty"));
    }
    headers = JoseHeader.from(headers).type(JOSEObjectType.JWT.getType()).keyId(jwk.getKeyID()).build();
    claims = JwtClaimsSet.from(claims).id(UUID.randomUUID().toString()).build();
    JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers);
    JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
    JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> {
        try {
            return JWS_SIGNER_FACTORY.createJWSSigner(key);
        } catch (JOSEException ex) {
            throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex);
        }
    });
    SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
    try {
        signedJwt.sign(jwsSigner);
    } catch (JOSEException ex) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
    }
    String jws = signedJwt.serialize();
    return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Jwt(org.springframework.security.oauth2.jwt.Jwt) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Aggregations

JWSHeader (com.nimbusds.jose.JWSHeader)4 JWSSigner (com.nimbusds.jose.JWSSigner)3 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)3 SecurityContext (com.nimbusds.jose.proc.SecurityContext)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)3 SignedJWT (com.nimbusds.jwt.SignedJWT)3 Instant (java.time.Instant)3 MockWebServer (okhttp3.mockwebserver.MockWebServer)3 Test (org.junit.jupiter.api.Test)3 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)2 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 MACSigner (com.nimbusds.jose.crypto.MACSigner)2 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 DefaultJOSEObjectTypeVerifier (com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier)2 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)2 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)2 BadJWTException (com.nimbusds.jwt.proc.BadJWTException)2 DefaultJWTProcessor (com.nimbusds.jwt.proc.DefaultJWTProcessor)2 JWTProcessor (com.nimbusds.jwt.proc.JWTProcessor)2