Search in sources :

Example 6 with JSONWebKeySet

use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.

the class OIDCWellKnownProviderTest method certs.

@Test
public void certs() throws IOException {
    TokenSignatureUtil.registerKeyProvider(Algorithm.ES256, adminClient, testContext);
    OIDCConfigurationRepresentation representation = SimpleHttp.doGet(getAuthServerRoot().toString() + "realms/test/.well-known/openid-configuration", client).asJson(OIDCConfigurationRepresentation.class);
    String jwksUri = representation.getJwksUri();
    JSONWebKeySet jsonWebKeySet = SimpleHttp.doGet(jwksUri, client).asJson(JSONWebKeySet.class);
    assertEquals(2, jsonWebKeySet.getKeys().length);
}
Also used : JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) OIDCConfigurationRepresentation(org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) BrowserFlowTest(org.keycloak.testsuite.forms.BrowserFlowTest) Test(org.junit.Test) LevelOfAssuranceFlowTest(org.keycloak.testsuite.forms.LevelOfAssuranceFlowTest)

Example 7 with JSONWebKeySet

use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.

the class OIDCAdvancedRequestParamsTest method assertRequestObjectEncryption.

private void assertRequestObjectEncryption(JWEHeader jweHeader) throws Exception {
    TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject requestObject = new TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject();
    requestObject.id(KeycloakModelUtils.generateId());
    requestObject.iat(Long.valueOf(Time.currentTime()));
    requestObject.exp(requestObject.getIat() + Long.valueOf(300));
    requestObject.nbf(requestObject.getIat());
    requestObject.setClientId(oauth.getClientId());
    requestObject.setResponseType("code");
    requestObject.setRedirectUriParam(oauth.getRedirectUri());
    requestObject.setScope("openid");
    byte[] contentBytes = JsonSerialization.writeValueAsBytes(requestObject);
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        OIDCConfigurationRepresentation representation = SimpleHttp.doGet(getAuthServerRoot().toString() + "realms/" + oauth.getRealm() + "/.well-known/openid-configuration", httpClient).asJson(OIDCConfigurationRepresentation.class);
        String jwksUri = representation.getJwksUri();
        JSONWebKeySet jsonWebKeySet = SimpleHttp.doGet(jwksUri, httpClient).asJson(JSONWebKeySet.class);
        Map<String, PublicKey> keysForUse = JWKSUtils.getKeysForUse(jsonWebKeySet, JWK.Use.ENCRYPTION);
        String keyId = jweHeader.getKeyId();
        if (keyId == null) {
            KeysMetadataRepresentation.KeyMetadataRepresentation encKey = KeyUtils.getActiveEncKey(testRealm().keys().getKeyMetadata(), org.keycloak.crypto.Algorithm.PS256);
            keyId = encKey.getKid();
        }
        PublicKey decryptionKEK = keysForUse.get(keyId);
        JWE jwe = new JWE().header(jweHeader).content(contentBytes);
        jwe.getKeyStorage().setEncryptionKey(decryptionKEK);
        oauth = oauth.request(jwe.encodeJwe());
        oauth.doLogin("test-user@localhost", "password");
        events.expectLogin().assertEvent();
    }
}
Also used : KeysMetadataRepresentation(org.keycloak.representations.idm.KeysMetadataRepresentation) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) PublicKey(java.security.PublicKey) JWE(org.keycloak.jose.jwe.JWE) TestingOIDCEndpointsApplicationResource(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource) OIDCConfigurationRepresentation(org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)

Example 8 with JSONWebKeySet

use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.

the class OIDCLoginProtocolService method certs.

@GET
@Path("certs")
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response certs() {
    checkSsl();
    JWK[] jwks = session.keys().getKeysStream(realm).filter(k -> k.getStatus().isEnabled() && k.getPublicKey() != null).map(k -> {
        JWKBuilder b = JWKBuilder.create().kid(k.getKid()).algorithm(k.getAlgorithmOrDefault());
        List<X509Certificate> certificates = Optional.ofNullable(k.getCertificateChain()).filter(certs -> !certs.isEmpty()).orElseGet(() -> Collections.singletonList(k.getCertificate()));
        if (k.getType().equals(KeyType.RSA)) {
            return b.rsa(k.getPublicKey(), certificates, k.getUse());
        } else if (k.getType().equals(KeyType.EC)) {
            return b.ec(k.getPublicKey());
        }
        return null;
    }).filter(Objects::nonNull).toArray(JWK[]::new);
    JSONWebKeySet keySet = new JSONWebKeySet();
    keySet.setKeys(jwks);
    Response.ResponseBuilder responseBuilder = Response.ok(keySet).cacheControl(CacheControlUtil.getDefaultCacheControl());
    return Cors.add(request, responseBuilder).allowedOrigins("*").auth().build();
}
Also used : X509Certificate(java.security.cert.X509Certificate) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) PathParam(javax.ws.rs.PathParam) RealmsResource(org.keycloak.services.resources.RealmsResource) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Constants(org.keycloak.models.Constants) Path(javax.ws.rs.Path) TokenRevocationEndpoint(org.keycloak.protocol.oidc.endpoints.TokenRevocationEndpoint) CacheControlUtil(org.keycloak.services.util.CacheControlUtil) KeyType(org.keycloak.crypto.KeyType) Messages(org.keycloak.services.messages.Messages) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) AuthorizationEndpoint(org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint) OAuthErrorException(org.keycloak.OAuthErrorException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) EventBuilder(org.keycloak.events.EventBuilder) LoginStatusIframeEndpoint(org.keycloak.protocol.oidc.endpoints.LoginStatusIframeEndpoint) ClientConnection(org.keycloak.common.ClientConnection) UriBuilder(javax.ws.rs.core.UriBuilder) Cors(org.keycloak.services.resources.Cors) TokenEndpoint(org.keycloak.protocol.oidc.endpoints.TokenEndpoint) LogoutEndpoint(org.keycloak.protocol.oidc.endpoints.LogoutEndpoint) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) JWK(org.keycloak.jose.jwk.JWK) KeycloakSession(org.keycloak.models.KeycloakSession) UserInfoEndpoint(org.keycloak.protocol.oidc.endpoints.UserInfoEndpoint) OIDCExtProvider(org.keycloak.protocol.oidc.ext.OIDCExtProvider) HttpRequest(org.jboss.resteasy.spi.HttpRequest) ThirdPartyCookiesIframeEndpoint(org.keycloak.protocol.oidc.endpoints.ThirdPartyCookiesIframeEndpoint) OPTIONS(javax.ws.rs.OPTIONS) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) NotFoundException(javax.ws.rs.NotFoundException) JWKBuilder(org.keycloak.jose.jwk.JWKBuilder) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) NoCache(org.jboss.resteasy.annotations.cache.NoCache) KeyUse(org.keycloak.crypto.KeyUse) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) UriInfo(javax.ws.rs.core.UriInfo) Collections(java.util.Collections) Response(javax.ws.rs.core.Response) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) JWKBuilder(org.keycloak.jose.jwk.JWKBuilder) X509Certificate(java.security.cert.X509Certificate) JWK(org.keycloak.jose.jwk.JWK) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 9 with JSONWebKeySet

use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.

the class ClientPublicKeyLoader method loadKeys.

@Override
public Map<String, KeyWrapper> loadKeys() throws Exception {
    OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientModel(client);
    if (config.isUseJwksUrl()) {
        String jwksUrl = config.getJwksUrl();
        jwksUrl = ResolveRelative.resolveRelativeUri(session, client.getRootUrl(), jwksUrl);
        JSONWebKeySet jwks = JWKSHttpUtils.sendJwksRequest(session, jwksUrl);
        return JWKSUtils.getKeyWrappersForUse(jwks, keyUse);
    } else if (config.isUseJwksString()) {
        JSONWebKeySet jwks = JsonSerialization.readValue(config.getJwksString(), JSONWebKeySet.class);
        return JWKSUtils.getKeyWrappersForUse(jwks, keyUse);
    } else if (keyUse == JWK.Use.SIG) {
        try {
            CertificateRepresentation certInfo = CertificateInfoHelper.getCertificateFromClient(client, JWTClientAuthenticator.ATTR_PREFIX);
            KeyWrapper publicKey = getSignatureValidationKey(certInfo);
            return Collections.singletonMap(publicKey.getKid(), publicKey);
        } catch (ModelException me) {
            logger.warnf(me, "Unable to retrieve publicKey for verify signature of client '%s' . Error details: %s", client.getClientId(), me.getMessage());
            return Collections.emptyMap();
        }
    } else {
        logger.warnf("Unable to retrieve publicKey of client '%s' for the specified purpose other than verifying signature", client.getClientId());
        return Collections.emptyMap();
    }
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) ModelException(org.keycloak.models.ModelException) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation)

Example 10 with JSONWebKeySet

use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.

the class OIDCIdentityProviderPublicKeyLoader method loadKeys.

@Override
public Map<String, KeyWrapper> loadKeys() throws Exception {
    if (config.isUseJwksUrl()) {
        String jwksUrl = config.getJwksUrl();
        JSONWebKeySet jwks = JWKSHttpUtils.sendJwksRequest(session, jwksUrl);
        return JWKSUtils.getKeyWrappersForUse(jwks, JWK.Use.SIG);
    } else {
        try {
            KeyWrapper publicKey = getSavedPublicKey();
            if (publicKey == null) {
                return Collections.emptyMap();
            }
            return Collections.singletonMap(publicKey.getKid(), publicKey);
        } catch (Exception e) {
            logger.warnf(e, "Unable to retrieve publicKey for verify signature of identityProvider '%s' . Error details: %s", config.getAlias(), e.getMessage());
            return Collections.emptyMap();
        }
    }
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet)

Aggregations

JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)18 PublicKey (java.security.PublicKey)7 Test (org.junit.Test)5 JWK (org.keycloak.jose.jwk.JWK)5 OIDCConfigurationRepresentation (org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)4 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)4 KeyWrapper (org.keycloak.crypto.KeyWrapper)3 CertificateRepresentation (org.keycloak.representations.idm.CertificateRepresentation)3 TestOIDCEndpointsApplicationResource (org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource)3 IOException (java.io.IOException)2 KeyPair (java.security.KeyPair)2 X509Certificate (java.security.cert.X509Certificate)2 List (java.util.List)2 GET (javax.ws.rs.GET)2 NotFoundException (javax.ws.rs.NotFoundException)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)2 NoCache (org.jboss.resteasy.annotations.cache.NoCache)2 OIDCAdvancedConfigWrapper (org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper)2