Selenium. Cookie. JWT token

In this post we’re going to figure out how to get a browser cookie using Selenium and decode a JWT token in a cookie.

Note: There is a lot of sources on the Internet that say why using JWT tokens in session management is a bad idea but since JWT tokens are still used by many sites we should be able to exctract, decode and validate them.

Let’s say we need to get a cookie named “SESSION_ID”. We can do it easily with Selenium

Cookie cookie = driver.manage().getCookieNamed("SESSION_ID");
String encodedToken  = cookie.getValue();

Here encodedToken is our encoded JWT token.

Decode JWT token

Decode JWT token

Now let’s decode the JWT token and get the payload. Usually JWT tokens look like this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

The payload is the part between .’s. We need to extract it and decode

String base64Payload = encodedToken.split("\\.")[1];
String decodedPayload = new String(Base64.getDecoder().decode(base64Payload));
System.out.println("Decoded payload: \n" + decodedPayload);

We will get

Decoded payload: 
{"sub":"1234567890","name":"John Doe","iat":1516239022}

You can check yourself if you decoded JWT token correctly - jwt.io

Decode JWT token - complete example

Let’s implement it a more elegant way.

Cookie cookie = driver.manage().getCookieNamed("SESSION_ID");
DecodedJWT jwt = DecodedJWT.decode(cookie);

DecodedJWT

DecodedJWT allows us to use a JWT token as an object with access to all data as its fields. We just need to call decode(..) to decode an encoded JWT token and instantiate it as an object.

import java.util.Base64;
import com.google.gson.Gson;
import org.openqa.selenium.Cookie;

public class DecodedJWT {

    private String sub;
    private String name;
    private Long iat;

    public static DecodedJWT decode(String encodedToken) {
        String decodedPayload = new String(Base64.getDecoder().decode(encodedToken.split("\\.")[1]));
        return new Gson().fromJson(decodedPayload, DecodedJWT.class);
    }

    public static DecodedJWT decode(Cookie cookie) {
        return decode(cookie.getValue);
    }

    public String getUserId() {
        return sub;
    }

    public void getName() {
        return name;
    }

    public Long getIssuedAt() {
        return iat;
    }
}

You may also find these posts interesting: