How are JSON Web Tokens Used?
JTWs are popular for a few reasons. First, of all, because the tokens require a server-side decryption, they can’t be easily manipulated by the user or a third party. They’re also compact (preventing a bloated post request) and self-contained, meaning they don’t require a followup request for data after the authentication is made.
Here’s how a JWT might be used alongside the user authentication process to allow a client to access their password-protected information:
- A user enters their login information and their credentials are posted to a server. Upon confirming that the user has entered the proper information, a JWT can be created.
- The JWT has three parts:
Header: The header contains indication that it is a JTW token, as well as the type of hashing algorithm used, both stored in JSON format. A hashing algorithm is a type of function used to encrypt and decrypt data.
This header is base64 encoded, meaning that its data is locked in a format that won’t be modified in the transmission process.
Payload: Also formatted in JSON, the payload contains the data being sent. This is where information such as a user’s id or unique username may be stored. This section can also store the token’s expiration date.
The resulting JSON is base64 encoded.
Signature: This takes the encoded header and payload, as well as the algorithm indicated in the header, and a generated secret to create a signature.
Finally, the token can be created in the correct format: three parts separated by dots:
3. The created JWT token is sent back to the client in the request’s response.
4. The token is stored in the client’s local browser storage so that it won’t be lost upon the page refreshing.
5. Every time the user requests information that is protected, the token is sent along in the header of the post request.
6. Each time the access token is sent with a request, it can be decoded using the secret stored on the server-side. No database query is needed to authenticate the request. The signature verifies that the token is coming from the right sender and that the data is not manipulated.
Note: I’ve referred to a secret key used to verify the token. The key is like a password that can be used to unlock private information. Just like a password, it can be changed and should be stored in a secure place. The HMAC algorithm uses a secret to encode and decode. RSA is another algorithm that uses public and private keys. Either system can be used with JWT.
- Introduction to JSON Web Tokens
- Wikipedia – JSON Web Token
- Vandium Software – 5 Easy Steps to Understanding JSON Web Tokens (JWT)
- Stack Abuse – Understanding JSON Web Tokens (JWT)
- Auth0 – Get Started with JSON Web Tokens
- Stack Overflow – Why do we use Base64?
- Wikipedia – Base64
- Wikipedia – Single sign on
- Wikipedia – Hash-based message authentication code
- Wikipedia – RSA (cryptosystem)