What is JWT — JSON web token

Time:2020-10-15

What is JWT

JSON web token (JWT) is an open standard based on JSON (RFC 7519) for the purpose of passing statements between network application environments. The token is designed to be compact and secure, especially suitable for single sign on (SSO) scenarios of distributed sites. JWT statement is generally used to transfer the authenticated user identity information between identity provider and service provider, so as to obtain resources from resource server. It can also add some additional declaration information required by other business logic. The token can also be directly used for authentication and can be encrypted.

origin

Speaking of JWT, we should talk about the difference between token based authentication and traditional session authentication.

Token based authentication mechanism

The authentication mechanism based on token is stateless, similar to HTTP protocol. It doesn’t need to reserve the user’s authentication information or session information at the server. This means that the application based on token authentication mechanism does not need to consider which server the user logs in, which provides convenience for the application expansion.

The process is as follows:

  • The user uses the user name and password to request the server
  • The server verifies the user’s information
  • The server sends a token to the user through authentication
  • The client stores the token and attaches the token value to each request
  • The server verifies the token value and returns the data

This token must be passed to the server every time it is requested. It should be saved in the request header. In addition, the server should support itCORS (cross source resource sharing)Strategy. Generally, we can do this on the server sideAccess-Control-Allow-Origin: *

So let’s go back to JWT.

What does JWT look like?

JWT is composed of three pieces of information.The links together make up the JWT string. Like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Composition of JWT

The first part is called the head, the second part is the payload, and the third part is the signature

header

The head of JWT carries two parts of information

  • Declaration type, here is JWT
  • The usual direct declaration encryption algorithm of hma256 is sha256

The complete header looks like the following JSON:

{
  'typ': 'JWT',
  'alg': 'HS256'
}

Then the header is encrypted with Base64 (the encryption can be decrypted symmetrically) to form the first part

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

playload

A load is a place where valid information is stored. The name seems to refer specifically to the goods carried on the aircraft, and the valid information contains three parts

  • Declaration registered in the standard
  • Public statement
  • Private statement

Declaration registered in the standard(recommended but not mandatory)

  • iss: JWT signer
  • sub: the users JWT is targeting
  • aud: the party receiving JWT
  • exp: the expiration time of JWT, which must be greater than the issue time
  • nbf: defines when the JWT is not available
  • iat: JWT issue time
  • jti: the unique identity of JWT, which is mainly used as a one-time token to avoid replay attacks.

Public statement
Any information can be added to the public statement. Generally, the user’s relevant information or other necessary information required by the business can be added. However, it is not recommended to add sensitive information, because this part can be decrypted at the client

Private statement
Private statement is defined by both provider and consumer. It is generally not recommended to store sensitive information because Base64 is symmetric decrypted, which means that this part of information can be classified as plaintext information.

Define a payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Then, it is encrypted with Base64 to get the second part of JWT.

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

signature

The third part of JWT is a visa information, which consists of three parts:

  • Header (after Base64)
  • Payload (after Base64)
  • secret

This part needs Base64 encrypted header and Base64 encrypted payload.Connect the string, and then add salt through the encryption method declared in the headersecretCombined encryption, which then forms the third part of JWT.

// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);

var signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Use these three parts.Concatenated into a complete string, forming the final JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Note: the secret is stored on the server side, and the JWT sign off generation is also on the server side. Secret is used to sign and verify JWT. Therefore, it is the private key of your server and should not be disclosed in any scenario. Once the client knows the secret, it means that the client can sign JWT by itself.

How to apply

It is usually added in the request headerAuthorizationAnd addBearertagging:

fetch('api/user/1', {
  headers: {
    'Authorization': 'Bearer ' + token
  }
})

The server will verify the token and return the corresponding resources if the verification is passed. The whole process is like this:

 
What is JWT -- JSON web token
jwt-diagram

summary

advantage

  • Because of the versatility of JSON, JWT can support cross language, such as Java, JavaScript, nodejs, PHP and many other languages.
  • With the payload part, JWT can store some non sensitive information necessary for other business logic on its own.
  • It is easy to transfer. The composition of JWT is very simple and the byte occupation is very small, so it is very easy to transfer.
  • It does not need to save session information on the server side, so it is easy to extend the application

shortcoming: it is also self parsing, and the server cannot manage, log off, refresh, and extend the validity period of the token. For example, I found that the account may have been stolen, so I went to change the password, but after changing the password, the original JWT can still be unimpeded. In order to solve this problem, the server will still persist the token. Once the token is persisted, there is no need to use JWT. The third section of JWT and his encryption certificate are redundant.

 

Safety related

  • You should not store sensitive information in the payload section of JWT, which is the decryptable part of the client.
  • Protect the secret private key, which is very important.
  • If you can, use the HTTPS protocol

 

The author is still learning. If you find any mistakes, please leave a message in the comment area. If you think the article is OK, please recommend it. Thank you!!