Decode JWT token in Java

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

Let’s asume we’ve got a 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.

You can use the online service jwt.io to decode the JWT token and get the content of the token. In the “PAYLOAD: DATA” section you’ll see.

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

Decode JWT token in Java.

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

Here we use Base64 decoding to decode a JWT token.

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. We encapsulate the JWT decoding functionality in the DecodedToken class

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 in Java

DecodedToken token = DecodedToken.getDecoded(stringToken);

Now you can access any field of the JWT token

if (token.admin) {
    System.out.println("Welcome sir " + token.name);
} else {
    System.out.println("Get out!!!");
}

You may also find these posts interesting: