'Detect if Authorization Header is JWT or OAUTH

My servlet receives the Authorization Header as "Bearer JWT_TOKEN" or "Bearer OAUTH_TOKEN".

How can I identify if the token is JWT or OAUTH?



Solution 1:[1]

Not sure what you mean by an OAUTH token, but to identify a JWT you can check if the token contains three parts separated by dots, if it's a signed JWT, or five parts, if it's an encrypted JWT.

So something like this for a signed JWT:

if (token.split("\\.").length == 3) {
   // It's a JWT
}

If you only have these two types of tokens, and you are sure that the OAUTH token is not formatted with two dots, then you easily differentiate those two types.

Another thing you can do is to pass the token to a JWT verification library and catch any exceptions. You will get something like a "Malformed token exception" if the token is not a JWT. Then you can assume that it's an OAUTH token.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michal Trojanowski