OAuth 2.0 | JSON Web Token (JWT) | How to validate?
In last two articles, we talked about JWT Claims and structure, therefore this article assumes we know how a JWT looks like and its different components along with their meaning and importance.
As we are studying OAuth, we also know that the primary use case of JWT is authorisation. We want to access protected resources kept at a resource server with the help of a JWT. Therefore, it becomes very important to understand the steps/process for validating a JWT.
Time to see image from one of the older articles. (https://www.techlearnings.org/single-post/oauth-2-0-access-refresh-tokens)
How a token is passed to server ?
The JWT is usually passed as Authorization header using Bearer schema in request to the resource server.
Authorization: bearer <jwt>
Coming to the important validation part now. (Please go to jwt.io and try playing with a token, it immediately validates and tells whether a token is valid or not)
The RFC framework specifies following steps to validate a JWT. If any of the step fails, then token is simply invalid.
At least one period ('.') character should be there.
Encoded header should be before the first period character.
Base64 decode the header and check for any line breaks, extra white spaces, or additional characters. If found, reject the token else move to next step.
Decoded header must be a completely valid JSON object.
Check header to make sure it has key value pairs which are supported.
With 5 steps explained above, do you really think, we need to know and implement all these steps by ourselves?
Not to mention, above mentioned steps are just for headers; we have payload and signature as well to validate. One small miss can lead to big security vulnerability in our application. Hence, it's not recommended to manually implement the steps, rather leverage the libraries written by experts to create/validate tokens. Ultimately, it boils down to validate structure and values.
I request to visit, https://jwt.io/libraries . There are libraries written in almost all programming languages. You can also see different functions and algorithms supported by each library. Pasting a snippet from that page below for Java.
We'll see practical demonstration soon as we've covered the fundamentals in a good amount of depth. That's it for today. Please visit https://datatracker.ietf.org/doc/html/rfc7519#section-7.2 , if you still wish to learn all validation steps.
We understand now what library is doing internally. Implementation of how part, let's leave it to experts.
Do stay connected, LinkedIn, Facebook, Twitter, YouTube wherever you feel comfortable. See you soon with next article!
Mentioning other OAuth articles already published as a handy reference guide for further learning. Do check out in case you missed/want to re-read.