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?
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With