Keycloak - Retrieve RSA public key
Asked Answered
Q

4

18

I have an app deployed with docker, one of the microservices is a jboss/keycloak server. Everything works fine, but keycloak RSA public key need to be retrieved manually. Is it possible to retrieve RSA public key through REST API?

Quip answered 14/7, 2018 at 10:6 Comment(0)
U
29

The url https://<keycloak-server>/auth/realms/<realm> contains a json response with the public key. This isn't advertised so it may change or go away. Using https://<keycloak-server>/auth/realms/<realm>/protocol/openid-connect/certs and setting up something to monitor the jwks response would be a much more maintainable way of handling it.

Uball answered 5/2, 2019 at 0:46 Comment(0)
P
8

Since version 14 or so, this is now https://<keycloak-server>/realms/<realm>, i.e., no /auth in the path anymore.

Pastelki answered 30/6, 2022 at 13:56 Comment(1)
/auth part disappeared between version 16 and 19. 16.1.1 has it but 19.0.1 does not.Bellbird
L
5

First, get the jwks_uri endpoint (JSON Web Key Sets):

The JSON Web Key Set (JWKS) is a set of keys containing the public keys used to verify any JSON Web Token (JWT) issued by the Authorization Server and signed using the RS256 signing algorithm.

To get that endpoint, use the .well-known endpoint, either by explicitly calling it:

<keycloak_host>/realms/DeepUnity/.well-known/openid-configuration

where <keycloak_host> might contain /auth depending on the Keycloak version (and configuration) that you have.

Or via Keycloak admin console (both in the old and new UI) under your Realm > Realm Settings > General then click on OpenID Endpoint Configuration.

Extract, and call the jwks_uri endpoint:

curl <keycloak_host>/realms/<REALM_NAME>/protocol/openid-connect/certs

which would return you something like:

{
   "keys":[
      {
         "kid":"...",
         "kty":"RSA",
         "alg":"RS256",
         "use":"sig",
         "n":"....",
         "e":"...",
         "x5c":[
            "blablabla"
         ],
         "x5t":"...",
         "x5t#S256":"..."
      },
      {
         ...
      }
   ]
}

with a (matching) KID ((Key ID) Header Parameter), one can get the certificate (${cert}) from the field x5c ((X.509 Certificate Chain) Header Parameter), in this example "blablabla". With that certificate one can extract the public key, for instance by executing the commands:

cat <<EOF > cert.pem
-----BEGIN CERTIFICATE-----
${cert}
-----END CERTIFICATE-----
EOF

and then

openssl x509 -in cert.pem -pubkey -noout
London answered 16/9, 2023 at 11:55 Comment(0)
B
3

Just for lazy people, as mentioned by @davidav. It means you get the regular openid-connect keys via

https://<keycloakserver>/realms/<realm>/protocol/openid-connect/certs
Brannen answered 20/8, 2022 at 7:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.