Cookie authentication mechanism

1. The user sends the user name and password to the server.

2. After the server passes the authentication, it saves relevant data in the current session, such as user role, login time and so on.

3. The server returns a session_ID to the user and writes the Cookie to the user.

4. Each subsequent request from the user will pass the session_ID back to the server via Cookie.

5. The server receives the session_ID, finds the previously saved data, and knows the user’s identity.

Token Authentication mechanism

I have always thought that cookie and token are the same, that is, the background returns a string and saves it in the front end, and the subsequent requests carry this string, and the background does verification. After in-depth understanding, I know that the two are very different, and they are two different mechanisms.

Cookie authentication requires the background to save a copy of session_ID to the database. If multiple servers are used, session sharing is required. Token authentication does not need to be saved in the background. Tokens are generally stored in the Authorization of HTTP request headers.

JWT

JSON Web Token (JWT) is an open standard that uses digital signatures to securely transfer information. Common JWT scenarios are Authorization and Information Exchange. Authorization is the most common JWT scenario.

JWT is a string delimited by ‘. ‘This string contains three parts: Header, Payload, and Signature. So the form of JWT is xxXXX.yyyyy.zzzzz.

JWT implements token authentication

1. Install the JsonWebToken dependency in the Express project

npm i jsonwebtoken --save
Copy the code

2. The new authorization. Js

const jwt = require("jsonwebtoken"); const secretKey = "secretKey"; / / generated token module. Exports. GenerateToken = function (content) {const token = "Bearer" + JWT. Sign (payload, secretKey. { expiresIn: 60 * 60, }); return token; }; / / authentication token module. Exports. VerifyToken = function (the req, res, next) { const token = req.headers.authorization.split(" ")[1]; jwt.verify(token, secretKey, function (err, decoded) { if (err) { console.log("verify error", err); Return res.json({code: "404", MSG: "token invalid "}); } console.log("verify decoded", decoded); next(); }); };Copy the code

Note: the token is generated with the prefix “Bearer” when, should remove the “Bearer” when validation, the req. Headers. Authorization. The split (” “) [1], can appear otherwise JsonWebTokenError: The authentication fails because the invalid token is incorrect.

3. Register the middleware in app.js

const auth = require("./authorization"); app.use("/api/login", loginRouter); app.use("/api/*", auth.verifyToken); // Register the token verification middlewareCopy the code

Note: The middleware that authenticates the token should be placed after the login route and before any other routes that need to be authenticated

Reference links:

JWT. IO/introductio…

Github.com/auth0/node-…

www.ruanyifeng.com/blog/2018/0…