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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With