bhanu
bhanu

Reputation: 258

Check if bearer token is jwt or not

I have two types of tokens coming in for a http request. One has a JWT token in the authorization header and other has a fixed length oauth token. Based on the type of token, I want to perform some action. How do I differentiate them?

I have tried

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
    public static void main(String[] args) {

      String pattern="^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.^[A-Za-z0-9-_.+/=]*$";
      String line="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MTYyMzkwMjJ9tbD.epxpstvGdW8TC3G8zg4B6rUYAOvfzdceoH48wgRQ";
      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(line);
      if (m.find( )) {  //is jwt
         System.out.println("jwt token");
      }else {
         System.out.println("NOt jwt");
      }
    }
}

but this is not working as expected. Is there any library which does this? Or can we modify the above regex?

Upvotes: 4

Views: 11074

Answers (4)

Nowhere Man
Nowhere Man

Reputation: 19555

The following regexp seems to be working:

    String pattern = "^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_.+/=]*$";

Upvotes: 0

Henry
Henry

Reputation: 43738

This regexp should work:

String pattern="^[A-Za-z0-9\\-_=]+\\.[A-Za-z0-9\\-_=]+(\\.[A-Za-z0-9\\-_.+/=]+)?$";

Upvotes: 0

mystery
mystery

Reputation: 935

You can follow alternative approach. A JWT token has three parts.Header info containing type and algorithm, payload and signature. Header and Body part is Base64 Encoded. If you decode the header part you will token type.

From your example token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MTYyMzkwMjJ9tbD.epxpstvGdW8TC3G8zg4B6rUYAOvfzdceoH48wgRQ

So header part is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 After decode you will get {"alg":"HS256","typ":"JWT"} From decoded value you can determine whether it is a jwt token or not

Upvotes: 8

jaop
jaop

Reputation: 268

I think we can check the token is jwt or not in this way:

  • Check if the jwt can be splitted by "." in to three parts (header, payload, signature)
  • Check the header, if it can be base64-decoded
  • Check the token type in the decoded header, if it is jwt

The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

For example:

{ "alg": "HS256", "typ": "JWT" } Then, this JSON is Base64Url encoded to form the first part of the JWT.

https://jwt.io/introduction/

Upvotes: 5

Related Questions