This article describes how to implement user login through session and token in NodeJS

Start by building a service with Express

  • This can be seen in my other article, which focuses on the express+mysql practice of implementing login features

Express middleware

  • What does middleware do?The connection
    1. Execute any code.
    2. Modify the request and response objects.
    3. Terminates the request-response loop.
    4. Call the next middleware in the stack.
  • We need to know the user state when any interface accesses the server, there needs to be a unified processing, middleware can help us do this
  • We customize a middleware, which is responsible for detecting the user state when each interface requests the server.
Path/middleware/auth. Jsconst auth = (req, res, next) = > {
  /** * return error message ** / if session_id or token is passed 
  if (true) {
    next();
  } else {
    res.render('fail', { message: 'Please login first! '}}})Copy the code
  • So how do we use this middleware?
The path/routers/user. Js// Import the middleware we just customized
var { auth } = require('.. /middleware/auth');
// Use this middleware in the interface where you want to validate user information, as follows:
/* Edit the user */
router.post('/edit', auth, userCtl.editUser);
// Do not use interfaces that do not require verification
/* User login */
router.post('/signIn', userCtl.signIn);
Copy the code
  • Ok, we have completed the process of verifying the user status, now let’s talk about how to implement based on session and token.

Session implementation method

process

  1. After user login and user information verification, the server will store necessary user information into session or Redis and generate an ID, called session_id, through which user information can be obtained.
  2. Kind of cookies, setting cookies for sessionId = XXXXXX | checksum and sends the HTTP response, still set signature for every cookies, cookies are carried in the HTTP request, If there is a corresponding sessionId in the cookie of subsequent request verification, the user login status can be determined.

practice

  1. Cookie-session specifies the third-party package

    • npm install cookie-sessionDownload the dependent
    Var cookieSession = require('cookie-session'); app.use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) ```Copy the code
  2. When the user logs in successfully

Path controllers/user. Js// The user information is verified
 req.session.username = name; // I saved a user name in the cookie
Copy the code
  1. How to check?

This is where we use our custom middleware

Path/middleware/auth. Jsconst auth = (req, res, next) = > {
  const userName = req.session.username;
  if (userName) {
    next();
  } else {
    res.render('fail', { message: 'Please login first! '}}})Copy the code

Token implementation method

process

  1. The user logs in and the service succeeds after the user information is verifiedjwtEncrypts the necessary user information, generates a string of ciphertext called token here and returns the token to the front end.
  2. Subsequent interface requests server users to usejwtVerify that the token is normal to determine the user status.
  3. usejsonwebtokenThird-party packages
    • npm install jsonwebtokenDownload the dependent
    • Symmetric encryption usage
    Path controllers/user. Js// The user information is verified
     var token = jwt.sign({ password: password }, 'afeng666');
     res.render('success', { data: JSON.stringify({ token }), message: 'Login successful' })
    Copy the code
    • Symmetric encryption check
    Path/middleware/auth. Jsconst auth = (req, res, next) = > {
        let token = req.get('x-token');
         // Capture decryption is normal
          try {
            var decoded = jwt.verify(token, 'afeng666');
            next();
          } catch (error) {
            res.render('fail', { message: 'Please login first! '}); }}Copy the code
    • Asymmetric encryption usage (more secure than symmetric encryption)
    1. You need to download Openssl to generate public and private keys
    2. Post a download address
    3. After the Openssl installation is complete, run the following command in the openssl/bin directory, or run the global command.
    Run the following command to generate a public key: openssl genrsa -out rsa_private_key.pem 1024 Generate a private key: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pemCopy the code
    1. Then place the corresponding two files in your file.
    2. After user information is verified, use the private key to encrypt it.
    Path controllers/user. Js// The user information is verified
     const privateKey = fs.readFileSync(path.join(__dirname , '.. /rsa/rsa_private_key.pem'));
     Asymmetric encryption specifies the encryption method
     const token = jwt.sign({ password: password }, privateKey , { algorithm: 'RS256'});
     res.render('success', { data: JSON.stringify({ token }), message: 'Login successful' })
    Copy the code

    6. Use the public key to decrypt the comparison

Path/middleware/auth. Jsconst auth = (req, res, next) = > {
        let token = req.get('x-token');
        const publicKey = fs.readFileSync(path.join(__dirname, '.. /rsa/rsa_public_key.pem'));
       // Capture decryption is normal
        try {
          const result = jwt.verify(token, publicKey);
          next();
        } catch (error) {
          res.render('fail', { message: 'Please login first! '}); }}Copy the code

The above