Json Web Token
(updated: )
What is Json Web Token
A compact, URL-safe means of representing claims to be transferred between two parties.
The server side creates a signature with a preconfigured secret key, and send the signature with the content to client.
When the client visit the server again with the token, the server can verify the token to trust the content in the token, without looking up databases.1hash(user_info + secret_key)
Format
|
|
header
Base64Url encoded of json such as:1234{ "alg": "HS256", "typ": "JWT"}
Standard fields:
- Token type (typ)
- Content type (cty): This claim should always be
JWT
- Algorithm (alg):
HS256
payload
A.K.A claims, which are the statements of the users, and additional metadata.
Base64Url encoded of json such as:12345{ "sub": "1234567890", "name": "John Doe", "admin": true}
Standard fields:
- Issuer (iss): The principal that issued the token
- Subject (sub): The subject of the token
- Audience (aud): The claim or user that the token is issued for
- Expiration time (exp): Expiration time
- Not before (nbf): Similarly, the not-before time claim identifies the time on which the JWT will start to be accepted for processing.
- Issued at (iat) - The “iat” (issued at) claim identifies the time at which the JWT was issued
- JWT ID (jti) - case sensitive unique identifier of the token even among different issuers
signature
|
|
Putting all together
|
|
How it works
- Server generates a
secret
(prepare before startup) and make it secure, and avaialbe only to server. - Client requests for a token. (by using credential to identify the client is a valid client)
- Server generates a
token
with asecret
. - Server returns the
token
. - Client stores the
token
to local storage. - Client visits protected resources on server with the
token
.- Typically in the Authorization header
Authorization: Bearer <token>
- Server verifies the
token
‘s signature by creating a signature and comparing if the two are equal, then retrives client informations, without looking up databases.