JWT (JSON Web Token)¶
JSON Web Token is a standard for creating JSON access tokens that can assert a number of claims.
JWTs are stateless because servers do not need to store any session data in order to validate these tokens.
This is the structure of JWTs:
||Contains token metadata, such as the algorithm used to generate the signature.|
||Contains a set of claims. They can be standard or custom.|
||The token signature, used to to provide integrity and authenticity proof.|
The actual token is produced by the following function:
base64url(header) + '.' + base64url(payload) + '.' + base64url(signature)
The token can be safely passed into HTML and HTTP.
This table enumerates the standard fields that can be used inside a JWT header.
||Token type||If present, it is recommended to set this to
||Content type||If nested signing or encryption is employed, it is recommended to set this to
||Message authentication code algorithm||The issuer can freely set an algorithm to verify the signature on the token. However, some supported algorithms are insecure.|
|Any other field allowed by the JWS and JWE standards.|
This table enumerates the standard claims that can be used inside a JWT payload.
||Issuer||The principal that issued the JWT.|
||Subject||The subject of the JWT.|
||Audience||Lists the recipients that the JWT is intended for. If the principal processing the claim does not identify itself with a value in the
||Expiration Time||Identifies the expiration time on and after which the JWT must not be accepted for processing. The value must be a NumericDate (i.e. the number of seconds past
||Not Before||Identifies the time on which the JWT will start to be accepted for processing. The value must be a NumericDate.|
||Issued at||Identifies the time at which the JWT was issued. The value must be a NumericDate.|
||JWT ID||Case sensitive unique identifier of the token even among different issuers.|
How JWTs are commonly used¶
This is how JWTs are commonly used:
- The client requests a token by providing credentials to the issuer.
- The issuer validates the client's request and responds with the token.
- The client can use the token to access some protected resources. For such requests, the client typically sends the token in the
Authorizationheader, using the
Authorization: Bearer abc123...321cba.
How to validate a JWT¶
Here's how the JWT validation algorithm works:
- Deserialize the token.
- Validate the standard claims:
nbf. If you want to allow manual token expiration before the expiration date, you also need to check the token against a data store. By doing so, your tokens will not be stateless anymore.
- Validate the signature using the algorithm specified in the token's header.