apachejwtapache-commons-codec

How to decode JWT (Header and Body) in java using Apache Commons Codec?


I am looking decode the following JWT using Apache Commons Codec. How we can do that ?

    eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZ
WxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw

This should retrieve Header, Body and Signature part. Whats the code ?


Solution

  • Here you go:

    import org.apache.commons.codec.binary.Base64;
    @Test
        public void testDecodeJWT(){
            String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZWxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw";
            System.out.println("------------ Decode JWT ------------");
            String[] split_string = jwtToken.split("\\.");
            String base64EncodedHeader = split_string[0];
            String base64EncodedBody = split_string[1];
            String base64EncodedSignature = split_string[2];
    
            System.out.println("~~~~~~~~~ JWT Header ~~~~~~~");
            Base64 base64Url = new Base64(true);
            String header = new String(base64Url.decode(base64EncodedHeader));
            System.out.println("JWT Header : " + header);
    
    
            System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
            String body = new String(base64Url.decode(base64EncodedBody));
            System.out.println("JWT Body : "+body);        
        }
    

    The output below:

    ------------ Decode JWT ------------
    ~~~~~~~~~ JWT Header ~~~~~~~
    JWT Header : {"alg":"HS256"}
    ~~~~~~~~~ JWT Body ~~~~~~~
    JWT Body : {"sub":"test","roles":"ROLE_ADMIN","iss":"myself","exp":1471086381}