Decode JWT token in Java

JWT tokens are used very often for authentication purposes. Let’s try to get information encoded in tokens.

Let’s asume we’ve got an JWT authentication token from some authentication service. It might look like

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4g
RG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Structure of JWT authentication token

There is the information encoded in the JWT token.

If you go to jwt.io to get the content of the JWT token you’ll see in the “PAYLOAD: DATA” section

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

Decode JWT token.

Our goal is to get that information from a JWT token programmatically in Java code.

Here we use Base64 decoding to decode JWT

String[] pieces = encodedToken.split("\\.");
String b64payload = pieces[1];
String jsonString = new String(Base64.decodeBase64(b64payload), "UTF-8");

jsonString variable contains the JSON string we’re looking for. So now we know the structure of the JWT authentication token. Knowing that we can create the class DecodedToken

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

public class DecodedToken {

  public String sub;
  public String name;
  public Boolean admin;

  public static DecodedToken getDecoded(String encodedToken) throws UnsupportedEncodingException {
      String[] pieces = encodedToken.split("\\.");
      String b64payload = pieces[1];
      String jsonString = new String(Base64.decodeBase64(b64payload), "UTF-8");

      return new Gson().fromJson(jsonString, DecodedToken.class);
  }

  public String toString() {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      return gson.toJson(this);
  }

}

Decode JWT token. Usage example

DecodedToken token = DecodedToken.getDecoded(stringToken);

// Now you can operate any field of the token
if (token.admin) {
    System.out.println("Welcome sir " + token.name);
} else {
    System.out.println("Get out!!!");
}

You may also find these posts interesting: