Search in sources :

Example 1 with JwsAlgorithm

use of org.springframework.security.oauth2.jose.jws.JwsAlgorithm 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 JwsAlgorithm

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

the class OidcIdTokenDecoderFactoryTests method createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied.

@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
    Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
    this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
    ClientRegistration clientRegistration = this.registration.build();
    given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
    this.idTokenDecoderFactory.createDecoder(clientRegistration);
    verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
Also used : JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 3 with JwsAlgorithm

use of org.springframework.security.oauth2.jose.jws.JwsAlgorithm 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)

Example 4 with JwsAlgorithm

use of org.springframework.security.oauth2.jose.jws.JwsAlgorithm in project flow by vaadin.

the class JwtSecurityContextRepository method encodeJwt.

private String encodeJwt(Authentication authentication) throws JOSEException {
    if (authentication == null || trustResolver.isAnonymous(authentication)) {
        return null;
    }
    final Date now = new Date();
    final List<String> roles = authentication.getAuthorities().stream().map(Objects::toString).filter(a -> a.startsWith(ROLE_AUTHORITY_PREFIX)).map(a -> a.substring(ROLE_AUTHORITY_PREFIX.length())).collect(Collectors.toList());
    SignedJWT signedJWT;
    JWSHeader jwsHeader = new JWSHeader(jwsAlgorithm);
    JWKSelector jwkSelector = new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
    List<JWK> jwks = jwkSource.get(jwkSelector, null);
    JWK jwk = jwks.get(0);
    JWSSigner signer = new DefaultJWSSignerFactory().createJWSSigner(jwk, jwsAlgorithm);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(authentication.getName()).issuer(issuer).issueTime(now).expirationTime(new Date(now.getTime() + expiresIn * 1000)).claim(ROLES_CLAIM, roles).build();
    signedJWT = new SignedJWT(jwsHeader, claimsSet);
    signedJWT.sign(signer);
    return signedJWT.serialize();
}
Also used : JwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) JWKSelector(com.nimbusds.jose.jwk.JWKSelector) HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) Date(java.util.Date) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JOSEException(com.nimbusds.jose.JOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SaveContextOnUpdateOrErrorResponseWrapper(org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtGrantedAuthoritiesConverter(org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) JwtValidators(org.springframework.security.oauth2.jwt.JwtValidators) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Collectors(java.util.stream.Collectors) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) JWK(com.nimbusds.jose.jwk.JWK) Objects(java.util.Objects) List(java.util.List) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) AuthenticationTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver) JWSSigner(com.nimbusds.jose.JWSSigner) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) SecurityContext(org.springframework.security.core.context.SecurityContext) JwtException(org.springframework.security.oauth2.jwt.JwtException) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) AuthenticationTrustResolverImpl(org.springframework.security.authentication.AuthenticationTrustResolverImpl) JWKMatcher(com.nimbusds.jose.jwk.JWKMatcher) Authentication(org.springframework.security.core.Authentication) JWKSelector(com.nimbusds.jose.jwk.JWKSelector) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 5 with JwsAlgorithm

use of org.springframework.security.oauth2.jose.jws.JwsAlgorithm in project flow by vaadin.

the class JwtSecurityContextRepository method getJwtDecoder.

private JwtDecoder getJwtDecoder() {
    if (jwtDecoder != null) {
        return jwtDecoder;
    }
    DefaultJWTProcessor<com.nimbusds.jose.proc.SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
    jwtProcessor.setJWTClaimsSetVerifier((claimsSet, context) -> {
    // No-op, Spring Security’s NimbusJwtDecoder uses its own validator
    });
    JWSKeySelector<com.nimbusds.jose.proc.SecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, jwkSource);
    jwtProcessor.setJWSKeySelector(jwsKeySelector);
    NimbusJwtDecoder nimbusJwtDecoder = new NimbusJwtDecoder(jwtProcessor);
    nimbusJwtDecoder.setJwtValidator(issuer != null ? JwtValidators.createDefaultWithIssuer(issuer) : JwtValidators.createDefault());
    this.jwtDecoder = nimbusJwtDecoder;
    return jwtDecoder;
}
Also used : DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) SecurityContext(org.springframework.security.core.context.SecurityContext) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector)

Aggregations

JwsAlgorithm (org.springframework.security.oauth2.jose.jws.JwsAlgorithm)5 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 DefaultJWTProcessor (com.nimbusds.jwt.proc.DefaultJWTProcessor)3 SecretKeySpec (javax.crypto.spec.SecretKeySpec)3 Test (org.junit.jupiter.api.Test)3 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)3 SignatureAlgorithm (org.springframework.security.oauth2.jose.jws.SignatureAlgorithm)3 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)3 JWK (com.nimbusds.jose.jwk.JWK)2 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)2 SecurityContext (com.nimbusds.jose.proc.SecurityContext)2 SecurityContext (org.springframework.security.core.context.SecurityContext)2 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)2 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)2 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)2 Jwt (org.springframework.security.oauth2.jwt.Jwt)2 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 JOSEException (com.nimbusds.jose.JOSEException)1 JWSHeader (com.nimbusds.jose.JWSHeader)1 JWSSigner (com.nimbusds.jose.JWSSigner)1