Introduction to the

HTTP is known to be a stateless protocol, so how do Web applications keep users logged in?

If you are not sure about the advantages and disadvantages of cookies, sessions and tokens, or you want to know how to implement logins in practice, then this article is for you. It will introduce the advantages and disadvantages of cookies, sessions and tokens in the order of their development.

This article focuses on the following aspects:

  1. cookie.session.token(json web token,jwt)The difference between
  2. nodeIn thejwtThe application of

The body of the

So if we’re on the server side and a user comes in how do we know if they’re logged in or not?

After verifying the username and password, we can send the client a credential (isLogin = true) that, if present in the request, identifies him as the logged in user. The difference between cookies and sessions is where the credentials are stored. In other words, if the credential is stored on the client, it is a cookie. If the credentials are stored on the server, it is a session.

Client storage (cookie)

Cookie is actually a field in the HTTP header that can store essentially any information. It was used in the early days to implement logins, so it has a different meaning — client-side storage. Each browser request will automatically carry the credentials in the cookie, which is convenient for the server to verify, as follows:

Figure 1 SpongeBob requests to invoke the ‘/login’ interface. After Patrick passes the verification, spongeBob is given the login certificate ‘isLogin=true’

But here’s the problem:

Document. Cookie =”isLogin = true” :

Figure 2 SpongeBob directly modifies the cookie to skip login interface authentication to obtain data

Server Storage (Session)

Session originally refers to the session state between the client and the server. Since the credentials are stored in the server, the information stored in the server is called session.

Now the server decides to maintain the login status by sending the client only a key and then maintaining a key-value table. If the request contains a key and the corresponding value can be found in the table, it is considered valid:

Figure 3 SpongeBob requests to invoke the ‘/login’ interface. Patrick issues spongeBob with a ‘sessionID’ after passing the verification

In this way, even if SpongeBob modified the sessionID by himself, there is no corresponding record from Patrick, and the data cannot be obtained.

Session is a good solution, but the problem is: if there are multiple servers such as load balancing, the state table of each server must be synchronized, or separated for unified management, such as using services such as Redis.

Token

Is there any other way to log in?

The cookie method does not require the server to store, but the credentials are easy to be forged, so what is the way to determine whether the credentials are forged?

Like HTTPS, you can use signatures to help the server verify credentials.

JSON Web Token (JWT for short) is a Token that stores information in JSON format. Its structure is shown as follows:

Figure 4 Structure of the JSON Web Token

JWT consists of three parts: header, payload, and signature.

According to the official website:

  1. The head storeTokenIn the figure above, the type isjwt, the encryption algorithm isHS256)
  2. The load isTokenInformation to store (in the figure above, user name and nickname information is stored)
  3. The signature is obtained by encrypting the escaped header and payload with the key by the specified algorithm.

And then finally, let’s use these three parts. “, you can get a Token.

Using JWT to maintain login status, the server no longer needs to maintain the status table, it only sends an encrypted data token to the client, each request carries this encrypted data, and then decrypts and verifies whether it is valid. Because the data is encrypted, even if the user can modify the data, the hit rate is very low.

How does the client store tokens?

  1. There arecookieIn, though setHttpOnlyCan effectively preventXSSIn the attacktokenStolen, but also means that the client cannot obtaintokenTo set theCORSThe head.
  2. There aresessionStorageorlocalStorageIn, you can set headers to solve cross-domain resource sharing problems while also preventing themCSRFBut it needs to be consideredXSSTo prevent disclosure of credentials.

NodeIn theJWTThe use of

Using JWT in Node only takes two steps:

The first step is to use jsonWebToken middleware in your /login route to generate tokens:

const jwt = require('jsonwebtoken')
let token = jwt.sign({
      name: user name
    }, config.secret, {
      expiresIn: '24h'
    })
    res.cookie('token', token)

Copy the code

For details, see Github of JsonWebToken

Second, register the Express-JWT middleware in the Node entry file app.js for token validation:

const expressJwt = require('express-jwt')
app.use(expressJwt({
  secret: config.secret,
  getToken: (req) => {
    return req.cookies.token || null
  }
}).unless({
  path: [
    '/login']}))Copy the code

If getToken returns NULL, the middleware raises an UnauthorizedError exception:

app.use(function(err, req, res, next) {// The following error is thrown when token authentication failsif (err.name === 'UnauthorizedError') {   
      res.status(401).json({
        status: 'fail',
        message: 'Identity check expired, please log in again'}); }});Copy the code

Refer to Express-JWT’s Github for syntax

How to implement single sign-on

Assuming we log in with the same user on both computers and phones, the token generated by both logins is valid for the server, even though they are the same user. So the two tokens will not be invalid.

To implement single sign-on, the server only needs to maintain a table of mappings between userIDS and tokens. The token value is refreshed each time the login succeeds.

Before processing the business logic, use the decrypted userId to find the token in the mapping table and compare it with the token in the request to verify whether it is valid.

Figure 5 implements single sign-on

conclusion

One of the very basic and important skills of the front end is to implement login state. When I was learning this, I was confused about the difference between Cookie, Session and Token. Sessions are a better solution than cookies. Token becomes mainstream because it does not require additional storage management. But when it comes to single sign-on, the problem of multiple servers needing to synchronize their mapping tables also arises.

Welcome to discuss and correct in the comments section!

reference

  1. PiaoLing. Nodejs. P181
  2. Shanyue. JWT practices and comparisons to Sessions