Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i decode JWT using Keycloak

I am using Keycloak with Spring-Boot in my application. My browser client request keycloak to generate JWT and then sends this JWT to my ZUUL server which validates JWT using keycloak-spring adapter and then i have written a pre-filter to decodes JWT payload and extract username. I am using com.auth0.java-jwt library to decode JWT like in below snippet

 DecodedJWT dJWT=JWT.decode(header);
 String username=dJWT.getClaim("preferred_username").asString();

I was wondering if there is anyway i can do this without using external library. I want to use keycloak library to decode JWT explicitly. How can i achieve this?

like image 887
arjunagarwal Avatar asked Jan 05 '18 05:01

arjunagarwal


People also ask

Does Keycloak support JWT?

This demonstrates how to generate JWT token using Keycloak. This can be used to authenticate the API user as well as to enable OAuth 2.0 authorization for all OAuth protected APIs using OpenID Connect in the Storefront application. This can be used as an alternative to the Auth microservice.

Can you decode JWT without secret?

By design, anyone can decode a JWT and read the contents of the header and payload sections. But we need access to the secret key used to create the signature to verify a token's integrity.


1 Answers

You have to include keycloak's core library into your dependencies.
Gradle: compileOnly 'org.keycloak:keycloak-core:3.4.2.Final'

Then use the org.keycloak.TokenVerifier to parse the token.
Example:

try
{
  // deprecated: AccessToken token = RSATokenVerifier.create(tokenString).getToken();
  AccessToken token = TokenVerifier.create(tokenString, AccessToken.class).getToken();
  System.out.printf("iss = %s%n", token.getIssuer());
  System.out.printf("sub = %s%n", token.getSubject());
  System.out.printf("typ = %s%n", token.getType());
}
catch (VerificationException e)
{
  // some error handling
}

You can also activate various verifications on the RSATokenVerifier and in particular the signature validation by setting the public key:

RSATokenVerifier.create(tokenString).checkActive(true).publicKey(key).verify().getToken()

like image 128
Boomer Avatar answered Sep 28 '22 17:09

Boomer