Search in sources :

Example 1 with SecurityContext

use of com.nimbusds.jose.proc.SecurityContext 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 SecurityContext

use of com.nimbusds.jose.proc.SecurityContext in project spring-security by spring-projects.

the class NimbusJwtDecoderTests method decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson.

// gh-7290
@Test
public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() {
    RestOperations restOperations = mock(RestOperations.class);
    given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
    // @formatter:off
    JWTProcessor<SecurityContext> processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor();
    // @formatter:on
    NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor);
    jwtDecoder.decode(SIGNED_JWT);
    ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
    verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
    List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
    assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Also used : SecurityContext(com.nimbusds.jose.proc.SecurityContext) MediaType(org.springframework.http.MediaType) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test)

Example 3 with SecurityContext

use of com.nimbusds.jose.proc.SecurityContext in project spring-security by spring-projects.

the class NimbusJwtEncoderTests method encodeWhenKeysRotatedThenNewKeyUsed.

@Test
public void encodeWhenKeysRotatedThenNewKeyUsed() throws Exception {
    TestJWKSource jwkSource = new TestJWKSource();
    JWKSource<SecurityContext> jwkSourceDelegate = spy(new JWKSource<SecurityContext>() {

        @Override
        public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) {
            return jwkSource.get(jwkSelector, context);
        }
    });
    NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSourceDelegate);
    JwkListResultCaptor jwkListResultCaptor = new JwkListResultCaptor();
    willAnswer(jwkListResultCaptor).given(jwkSourceDelegate).get(any(), any());
    JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
    JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
    Jwt encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    JWK jwk1 = jwkListResultCaptor.getResult().get(0);
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk1).toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws.getTokenValue());
    // Simulate key rotation
    jwkSource.rotate();
    encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    JWK jwk2 = jwkListResultCaptor.getResult().get(0);
    jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk2).toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws.getTokenValue());
    assertThat(jwk1.getKeyID()).isNotEqualTo(jwk2.getKeyID());
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) RSAKey(com.nimbusds.jose.jwk.RSAKey) SecurityContext(com.nimbusds.jose.proc.SecurityContext) ArrayList(java.util.ArrayList) List(java.util.List) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 4 with SecurityContext

use of com.nimbusds.jose.proc.SecurityContext 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 5 with SecurityContext

use of com.nimbusds.jose.proc.SecurityContext 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)

Aggregations

SecurityContext (com.nimbusds.jose.proc.SecurityContext)9 RSAKey (com.nimbusds.jose.jwk.RSAKey)6 Test (org.junit.jupiter.api.Test)6 JWKSelector (com.nimbusds.jose.jwk.JWKSelector)5 JWK (com.nimbusds.jose.jwk.JWK)3 JWKSet (com.nimbusds.jose.jwk.JWKSet)3 SignatureAlgorithm (org.springframework.security.oauth2.jose.jws.SignatureAlgorithm)3 Jwt (org.springframework.security.oauth2.jwt.Jwt)3 JOSEException (com.nimbusds.jose.JOSEException)2 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 KeySourceException (com.nimbusds.jose.KeySourceException)2 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)2 Base64URL (com.nimbusds.jose.util.Base64URL)2 URL (java.net.URL)2 Instant (java.time.Instant)2 List (java.util.List)2 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)2 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 ImmutableList (com.google.common.collect.ImmutableList)1 Algorithm (com.nimbusds.jose.Algorithm)1