What is JSON Web Token?
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
When should you use JSON Web Tokens?
- Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
- Information Exchange: JWT are a good way of securely transmitting information between parties. Because JWT are digitally signed, you can be sure that the sender is who they say they are, and that the message hasn't been changed in any way.
What is the JSON Web Token structure?
In its compact form, JWT consist of three parts separated by dots (.), which are:
- Header
- Payload
- Signature
Therefore, a JWT typically looks like the following: xxxxx.yyyyy.zzzzz
Header
The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA.
For example:
{ "alg": "HS256", "type": "JWT" }
Payload
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims:
- Registered claims: These are a set of predefined claims which are recommended for implementation.
- Public claims: These can be defined at will by those using JWTs.
- Private claims: These are custom claims created to share information between parties that agree on using them.
For example:
{ "sub": "1234567890", "name": "John Doe", "admin": true }
Signature
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
The signature is used to verify that the sender of the JWT is who they say they are, and that the message hasn't been changed in any way.
How do JWTs work?
In a typical authentication flow, the user uses their credentials to log in. Once the user is logged in, the server creates a new JWT and sends it back to the client. The client then stores the JWT and includes it in the Authorization header of each subsequent request. The server verifies the signature of the JWT to ensure that it is valid.
The following diagram shows how JWTs are typically used:
JWTs are a powerful tool for authentication and authorization. They are lightweight, secure, and easy to use. If you are building a web application that needs to be secure, JWTs are a great option.
No Comments