How can i decode JWT using Keycloak

14,461

Solution 1

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()

Solution 2

As i am using keycloak to authenticate jwt, it decodes jwt and puts details into SecurityContextHolder and I just pulled the details from there it self. here is the code.

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
            KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) authentication.getPrincipal();
            // retrieving username here
            String username = kp.getKeycloakSecurityContext().getToken().getPreferredUsername();
            }
      }

this solved it for me.

Share:
14,461
arjunagarwal
Author by

arjunagarwal

Code for living. Love to solve problems.

Updated on June 04, 2022

Comments

  • arjunagarwal
    arjunagarwal almost 2 years

    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?