Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding Keycloak JWT Token

Tags:

keycloak

I'm trying to validate (and read roles from) a JWT Token. Sadly I can't use any adapter or auto configuration due to my overall application architecture.

It's no problem to decode the token like any other JWT Token, but I wonder if there is a library from Keycloak to archive this goal. (For example Just Parse the token to something like a KeycloakJWTToken and verify it by grabbing the secret from Keycloak Server or so)

Any easy-to-use client or so?

like image 204
pixel Avatar asked Aug 14 '26 10:08

pixel


2 Answers

I'm using the Jose4J library: https://bitbucket.org/b_c/jose4j/wiki/Home

Reading the claims inside a JWT token is straightforward:

import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;

public void parseJWT(String token) throws Exception {              
       JwtConsumer consumer = new JwtConsumerBuilder()
               .setSkipAllValidators()
               .setDisableRequireSignature()
               .setSkipSignatureVerification()
               .build();
       JwtClaims claims = consumer.processToClaims(token);       
       System.out.println("* Parsed token: "+ claims.getRawJson() );       
       System.out.println("* Expiration date: " + new Date(claims.getExpirationTime().getValueInMillis()) );       
}

More examples are available on GitHub: https://github.com/pvliesdonk/jose4j/blob/master/src/test/java/org/jose4j/examples/ExamplesTest.java

Last remark: you do not need a key nor a secret to parse the JWT, but if needed, you can use the server (public) key to verify the token was signed by the keycloak server you are trusting.

The JWT website is listing all libraries for Token Signing/Verification:

https://jwt.io/#libraries-io

like image 60
TacheDeChoco Avatar answered Aug 23 '26 12:08

TacheDeChoco


Keycloak access tokens are indeed JWT tokens. So, you can make full use of existing JWT libraries, including for validation as stated in the Keycloak official documentation:

If you need to manually validate access tokens issued by Keycloak you can invoke the Introspection Endpoint. The downside to this approach is that you have to make a network invocation to the Keycloak server. This can be slow and possibily overload the server if you have too many validation requests going on at the same time. Keycloak issued access tokens are JSON Web Tokens (JWT) digitally signed and encoded using JSON Web Signature (JWS). Because they are encoded in this way, this allows you to locally validate access tokens using the public key of the issuing realm. You can either hard code the realm’s public key in your validation code, or lookup and cache the public key using the certificate endpoint with the Key ID (KID) embedded within the JWS. Depending what language you code in, there are a multitude of third party libraries out there that can help you with JWS validation.

Besides, in Java EE, using the Keycloak Java adapter, the roles are typically mapped on the user Principal and i.e. allows isUserInRole(). That's one of the goals. Also it is possible to cast the Principal from the SecurityContext as a KeycloakPrincipal, then obtain in turn a KeycloakSecurityContext from it. Using the KeycloakSecurityContext you have access to both ID and Access tokens (when applicable) and can read their properties, attributes and claims.

Note that it is also good practice, and simply useful, to use the Keycloak UI to "evaluate" your tokens. For instance, you can see the generated token in the Client Scopes tab (under Evaluate), as well as evaluate your policies and permissions in the Authorization tab of your Client(s) (under Evaluate). Cf. https://www.keycloak.org/docs/latest/server_admin/#_client_scopes_evaluate That's probably the best way to debug and test, while setting up your Client(s).

If you select a user in the Evaluate screen, the following example data is generated:

  • Generated Access Token (...)
  • Generated ID Token (...)
  • Generated User Info (...)

All examples are generated for the particular user and issued for the particular client, with the specified value of scope parameter. The examples include all of the claims and role mappings used.

Source: https://www.keycloak.org/docs/latest/server_admin/#generating-example-tokens-and-user-info

like image 31
bsaverino Avatar answered Aug 23 '26 12:08

bsaverino