What are Json web token (JWT), session, token, advantages and disadvantages

Posted by creatives on Wed, 23 Feb 2022 05:45:51 +0100

JWT
----------------------------------------
Json web token (JWT) is an open standard based on JSON, which is implemented to transfer declarations between network application environments. The declaration of JWT is generally used to transfer the authenticated user identity information between identity providers and service providers, so as to obtain resources from the resource server. Some additional declaration information necessary for other business logic can also be added.
Traditional session authentication

Problems revealed by session based authentication

Session: after each user has been authenticated by our application, our application should make a record at the server to facilitate the authentication of the user's next request. Generally speaking, the session is saved in memory. With the increase of authenticated users, the cost of the server will increase significantly.

Scalability: after user authentication, the server makes authentication records. If the authentication records are saved in memory, it means that the user must request on this server next time, so as to get the authorized resources. In this way, in distributed applications, the ability of load balancer is correspondingly limited. This also means that the expansion ability of the application is limited.

CSRF: because user identification is based on cookies, if cookies are intercepted, users will be vulnerable to cross site request forgery attacks.

Authentication mechanism based on token

The token based authentication mechanism does not need to retain 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 expansion of the application.

The token authentication process is as follows:

advantage

  • Because of the versatility of json, JWT can be supported across languages. Many languages such as Java, JavaScript, nodejs, PHP and so on can be used.
  • JWT can store some non sensitive information necessary for other business logic in itself.
  • It is easy to transmit. The composition of jwt is very simple and the occupation of bytes is very small, so it is very easy to transmit.
  • It does not need to save the session information on the server, so it is easy to be extended.

Structure of JWT

JWT is composed of three pieces of information, which are used as text The links together form a JWT string. Like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

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

header

The header of jwt carries two parts of information:

  • Declaration type
  • Declare the algorithm of encryption (usually directly use HMAC SHA256)

The complete header is like the following JSON:

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

The header is encrypted with base64 (the encryption can be decrypted symmetrically), which constitutes the first part:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

payload

Payload is the place where valid information is stored. The name seems to refer specifically to the goods carried on the aircraft. The valid information includes three parts

  • Declaration registered in the standard
    • iss: jwt issuer
    • Sub: the user JWT is targeting
    • aud: party receiving jwt
    • Exp: the expiration time of JWT, which must be greater than the issuing time
    • nbf: define the time before which the jwt is unavailable
    • IAT: issuing time of JWT
    • 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 on the client
  • Private declaration

For example, define a payload json:

{
  "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 The string formed by connection is then encrypted by salt secret combination through the encryption method declared in the header, and then constitutes the third part of jwt.

// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
var signature = HMACSHA256(encodedString, 'secret');

Use these three parts Connected into a complete string to form the final jwt:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

JWT application (based on jsonwebtoken module)

To install jsonwebtoken:

npm install --save jsonwebtoken

Issuing token:

const jwt = require('jsonwebtoken')
const key = 'my key' // Define secret key

// Declare the load carried
let payload = {
    name: 'Zhang San',
    userId: 1003, 
    exp: Date.now()/1000 + 3600*24
}
let token = jwt.sign(payload, key)

Verify token:

app.get('/verifytoken', (req, res)=>{
    // Get Authorization header
    // console.log(req)
    let token = req.headers.authorization
    // Verify the token and obtain the payload data stored in the token
    jwt.verify(token, key, (err, decoded) => {
        console.warn(err)    // If validation fails, err will not be null
        console.log(decoded)
        res.send('OK')
    })
})

Implementation of verification code based on JWT


I hope it will be helpful to you

Topics: Front-end Session http tokenization