Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decode JWT token in android?

Tags:

java

android

jwt

I have a jwt token like this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ 

How can I decode this so that I can get the payload like this

{   "sub": "1234567890",   "name": "John Doe",   "admin": true } 

I have used this library , but can't find a way to do what I want

like image 335
aroM Avatar asked Jun 08 '16 07:06

aroM


People also ask

Can anyone decode a JWT token?

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.

How do you decode JWT without secret?

There are two ways in which a public/private keys can be used by a JWT: signing and encryption. If you use a private key for signing, it allows for the recipient to identify the sender of the JWT and the integrity of the message but not to hide its contents from others (confidentiality).


1 Answers

you should split string: If you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):

header

{   "alg": "HS256",   "typ": "JWT" } 

body

    {   "sub": "1234567890",   "name": "John Doe",   "admin": true } 

Code example:

public class JWTUtils {      public static void decoded(String JWTEncoded) throws Exception {         try {             String[] split = JWTEncoded.split("\\.");             Log.d("JWT_DECODED", "Header: " + getJson(split[0]));             Log.d("JWT_DECODED", "Body: " + getJson(split[1]));         } catch (UnsupportedEncodingException e) {             //Error         }     }      private static String getJson(String strEncoded) throws UnsupportedEncodingException{         byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);         return new String(decodedBytes, "UTF-8");     } } 

Call method for example

JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"); 

library reference: https://github.com/jwtk/jjwt

jwt test: https://jwt.io/

like image 130
Alex Zaraos Avatar answered Sep 21 '22 01:09

Alex Zaraos