How to verify that a string is JWT token?

Tags: ,

In Java How can we verify that i given String is a JWT Token without using Signature?

I am using

try {
     return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
     throw new IOException("Failed to parse");

This works fine but I want to verify this without SECRET_KEY.

I Just want to verify whether it is a JWT token or not.


Here is an example to check the structure of the JWT. You only need to add the validations of the data that the JWT should carry

boolean isJWT(String jwt) {
        String[] jwtSplitted = jwt.split("\.");
        if (jwtSplitted.length != 3) // The JWT is composed of three parts
            return false;
        try {
            String jsonFirstPart = new String(Base64.getDecoder().decode(jwtSplitted[0]));
            JSONObject firstPart = new JSONObject(jsonFirstPart); // The first part of the JWT is a JSON
            if (!firstPart.has("alg")) // The first part has the attribute "alg"
                return false;
            String jsonSecondPart = new String(Base64.getDecoder().decode(jwtSplitted[1]));
            JSONObject secondPart = new JSONObject(jsonSecondPart); // The first part of the JWT is a JSON
            //Put the validations you think are necessary for the data the JWT should take to validate
        }catch (JSONException err){
            return false;
        return true;

Source: stackoverflow