Search in sources :

Example 1 with JWKSet

use of com.nimbusds.jose.jwk.JWKSet in project java-docs-samples by GoogleCloudPlatform.

the class VerifyIapRequestHeader method getKey.

private ECPublicKey getKey(String kid, String alg) throws Exception {
    JWK jwk = keyCache.get(kid);
    if (jwk == null) {
        // update cache loading jwk public key data from url
        JWKSet jwkSet = JWKSet.load(new URL(PUBLIC_KEY_VERIFICATION_URL));
        for (JWK key : jwkSet.getKeys()) {
            keyCache.put(key.getKeyID(), key);
        }
        jwk = keyCache.get(kid);
    }
    // confirm that algorithm matches
    if (jwk != null && jwk.getAlgorithm().getName().equals(alg)) {
        return ECKey.parse(jwk.toJSONString()).toECPublicKey();
    }
    return null;
}
Also used : JWKSet(com.nimbusds.jose.jwk.JWKSet) URL(java.net.URL) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with JWKSet

use of com.nimbusds.jose.jwk.JWKSet 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 3 with JWKSet

use of com.nimbusds.jose.jwk.JWKSet in project dhis2-core by dhis2.

the class JwtBearerTokenTest method setUpClass.

@BeforeAll
static void setUpClass() throws JOSEException {
    DhisWebApiWebSecurityConfig.setApiContextPath("");
    JWKSource<SecurityContext> jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(new JWKSet(ImmutableList.of(RSA_KEY)));
    jwsEncoder = new JwtUtils(jwkSource);
    jwtDecoder = NimbusJwtDecoder.withPublicKey(RSA_KEY.toRSAPublicKey()).build();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SecurityContext(com.nimbusds.jose.proc.SecurityContext) ConfigurationKey(org.hisp.dhis.external.conf.ConfigurationKey) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Contracts.assertNotNull(org.hibernate.validator.internal.util.Contracts.assertNotNull) JOSEException(com.nimbusds.jose.JOSEException) Autowired(org.springframework.beans.factory.annotation.Autowired) DhisOidcProviderRepository(org.hisp.dhis.security.oidc.DhisOidcProviderRepository) JWKSet(com.nimbusds.jose.jwk.JWKSet) JwtClaimsSet(org.hisp.dhis.webapi.security.utils.JwtClaimsSet) TestJwks(org.hisp.dhis.webapi.security.utils.TestJwks) TestJwtClaimsSets(org.hisp.dhis.webapi.security.utils.TestJwtClaimsSets) Dhis2JwtAuthenticationManagerResolver(org.hisp.dhis.security.jwt.Dhis2JwtAuthenticationManagerResolver) ImmutableList(com.google.common.collect.ImmutableList) BeforeAll(org.junit.jupiter.api.BeforeAll) JsonError(org.hisp.dhis.webapi.json.domain.JsonError) DhisWebApiWebSecurityConfig(org.hisp.dhis.webapi.security.config.DhisWebApiWebSecurityConfig) JoseHeaderNames(org.hisp.dhis.webapi.security.utils.JoseHeaderNames) User(org.hisp.dhis.user.User) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) JwtTokenHeader(org.hisp.dhis.webapi.WebClient.JwtTokenHeader) Jwt(org.springframework.security.oauth2.jwt.Jwt) JsonUser(org.hisp.dhis.webapi.json.domain.JsonUser) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) Properties(java.util.Properties) TestJoseHeaders(org.hisp.dhis.webapi.security.utils.TestJoseHeaders) JoseHeader(org.hisp.dhis.webapi.security.utils.JoseHeader) DhisControllerWithJwtTokenAuthTest(org.hisp.dhis.webapi.DhisControllerWithJwtTokenAuthTest) GenericOidcProviderConfigParser(org.hisp.dhis.security.oidc.GenericOidcProviderConfigParser) Test(org.junit.jupiter.api.Test) HttpStatus(org.springframework.http.HttpStatus) RSAKey(com.nimbusds.jose.jwk.RSAKey) JwtUtils(org.hisp.dhis.webapi.security.utils.JwtUtils) DhisOidcClientRegistration(org.hisp.dhis.security.oidc.DhisOidcClientRegistration) GoogleProvider(org.hisp.dhis.security.oidc.provider.GoogleProvider) JWKSet(com.nimbusds.jose.jwk.JWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JwtUtils(org.hisp.dhis.webapi.security.utils.JwtUtils) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 4 with JWKSet

use of com.nimbusds.jose.jwk.JWKSet in project dhis2-core by dhis2.

the class JwtUtils method jwkSource.

public JWKSource<SecurityContext> jwkSource() {
    RSAKey rsaKey = Jwks.generateRsa();
    JWKSet jwkSet = new JWKSet(rsaKey);
    return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
Also used : SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWKSelector(com.nimbusds.jose.jwk.JWKSelector) URL(java.net.URL) Date(java.util.Date) JOSEException(com.nimbusds.jose.JOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWKSet(com.nimbusds.jose.jwk.JWKSet) JWSSignerFactory(com.nimbusds.jose.produce.JWSSignerFactory) Map(java.util.Map) Base64URL(com.nimbusds.jose.util.Base64URL) Jwt(org.springframework.security.oauth2.jwt.Jwt) Base64(com.nimbusds.jose.util.Base64) Converter(org.springframework.core.convert.converter.Converter) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) JWK(com.nimbusds.jose.jwk.JWK) KeySourceException(com.nimbusds.jose.KeySourceException) List(java.util.List) JWSSigner(com.nimbusds.jose.JWSSigner) RSAKey(com.nimbusds.jose.jwk.RSAKey) JSONObject(net.minidev.json.JSONObject) CollectionUtils(org.springframework.util.CollectionUtils) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) JWKMatcher(com.nimbusds.jose.jwk.JWKMatcher) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) RSAKey(com.nimbusds.jose.jwk.RSAKey) JWKSet(com.nimbusds.jose.jwk.JWKSet)

Example 5 with JWKSet

use of com.nimbusds.jose.jwk.JWKSet in project SEPA by arces-wot.

the class AuthorizationManager method init.

private boolean init(KeyStore keyStore, String keyAlias, String keyPwd) throws KeyStoreException, JOSEException {
    // Load the key from the key store
    RSAKey jwk = RSAKey.load(keyStore, keyAlias, keyPwd.toCharArray());
    // Get the private and public keys to sign and verify
    RSAPrivateKey privateKey;
    RSAPublicKey publicKey;
    privateKey = jwk.toRSAPrivateKey();
    publicKey = jwk.toRSAPublicKey();
    // Create RSA-signer with the private key
    signer = new RSASSASigner(privateKey);
    // Create RSA-verifier with the public key
    verifier = new RSASSAVerifier(publicKey);
    // Serialize the public key to be deliverer during registration
    jwkPublicKey = new JsonParser().parse(jwk.toPublicJWK().toJSONString());
    // Set up a JWT processor to parse the tokens and then check their signature
    // and validity time window (bounded by the "iat", "nbf" and "exp" claims)
    jwtProcessor = new DefaultJWTProcessor<SEPASecurityContext>();
    JWKSet jws = new JWKSet(jwk);
    JWKSource<SEPASecurityContext> keySource = new ImmutableJWKSet<SEPASecurityContext>(jws);
    JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
    JWSKeySelector<SEPASecurityContext> keySelector = new JWSVerificationKeySelector<SEPASecurityContext>(expectedJWSAlg, keySource);
    jwtProcessor.setJWSKeySelector(keySelector);
    return true;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JsonParser(com.google.gson.JsonParser)

Aggregations

JWKSet (com.nimbusds.jose.jwk.JWKSet)6 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 JWK (com.nimbusds.jose.jwk.JWK)3 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 ImmutableJWKSet (com.nimbusds.jose.jwk.source.ImmutableJWKSet)3 SecurityContext (com.nimbusds.jose.proc.SecurityContext)3 Jwt (org.springframework.security.oauth2.jwt.Jwt)3 JsonParser (com.google.gson.JsonParser)2 JOSEException (com.nimbusds.jose.JOSEException)2 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)2 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)2 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)2 URL (java.net.URL)2 RSAPublicKey (java.security.interfaces.RSAPublicKey)2 Instant (java.time.Instant)2 ImmutableList (com.google.common.collect.ImmutableList)1 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)1 JWSHeader (com.nimbusds.jose.JWSHeader)1 JWSSigner (com.nimbusds.jose.JWSSigner)1 KeySourceException (com.nimbusds.jose.KeySourceException)1