Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
bhanu Avatar asked Oct 25 '25 00:10

bhanu


1 Answers

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

like image 193
mystery Avatar answered Oct 26 '25 15:10

mystery