How to use node scaffolding to build a server to implement token verification

How to use node scaffolding to build a server to implement token verification

content

  • Use scaffolding to quickly build a node project
  • Use mysql connection pool to interact with the database
  • Implementing token authentication with jsonwebtoken
  • Comprehensive example: Implementing the above with an introductory login page

1. Quickly build a node project

We all know that the express framework can efficiently develop node servers, but the underlying construction still depends on handwriting. However, the emergence of express-generator solves this problem very well. It can generate the basic skeleton of the project for us with one click, which can be called node scaffolding

1.1 Generate Project

①: First install express globally: npm install express -g
②: Then install express-generator globally: npm install express-generator -g
③: Then use the command to create a project: express token_learn (project name)

1.2 Modify the entry file

For many people who are used to manually running servers, app.js is always unforgettable, but the entry file in this skeleton is www.js. At this point we can manually modify the app.js code to make it our entry file

Example:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');

const index = require('./routes/index');
const users = require('./routes/users');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

app.listen(3000, () => console.log('server is running 3000'))

2. Connect to MySQL database

The connection pool is used here for connection (efficient and safe)

2.1 Create a connection

①: Install mysql module: npm i mysql
②: Configure the connection pool in the project root directory

First, create a util folder in the project root directory and create a bdconfig.js file in the folder

bdconfig.js

const mysql = require('mysql');

module.exports = {
  mysqlParams: {
    host: 'localhost', //Domain name port: '3306', //Port user: 'root', //User name password: 'myroot', //Password database: 'nodeapi' //Database},
  sySqlConnect(sql, sqlArr) {
    return new Promise((resolve, reject) => { //Transform it with Promise object to facilitate receiving data const pool = mysql.createPool(this.mysqlParams);
      pool.getConnection((err, conn) => {
        if (err) {
          reject(err)
        } else {
          conn.query(sql, sqlArr, (err, data) => { //Operate databaseif (err) {
              reject(err)
            } else {
              resolve(data)
            }
          })
          conn.release() //Release the connection}
      })
    })
  }
}

2.2 Using Connections

When using it, you only need to pass in sql (sql statement) and sqlArr (parameters). After Promise transformation, you can directly use the return value to get the result

3. Token authentication

With the development of the web, the shortcomings of session and cookie authentication methods have become more and more prominent. At this time, tokens were born. The power of tokens is not limited to being stateless, but also that they can be used across domains.

3.1 Implementation steps

①: First install the jsonwebtoken module: npm i jsonwebtoken
②: Then use the module in the project

const dbConfig = require('../util/dbconfig');
const jwt = require('jsonwebtoken');
const secret = 'login-rule'; //Secret key rule (custom)

token = async(req, res, next) => { //Define token verification middleware function (applied to every request except login)
  if (req.headers.authorization) {
    const token = req.headers.authorization;
    const { id, username } = jwt.verify(token, secret); // Decrypt and find the token let sql = 'select * from test where id=?';
    let sqlArr = [id];
    let result = await dbConfig.sySqlConnect(sql, sqlArr);
    if (result.length === 0) {
      res.status(200).send({ msg: 'User error' })
      return
    }
    if (username !== result[0].username) {
      res.status(200).send({ msg: 'User error' })
    } else {
      next()
    }
  } else {
    res.status(200).send({ msg: 'Invalid request header' })
  }
}

login = async(req, res) => { //Define the login interface (because this request header does not carry a token, it is referenced before the token verification middleware)
  let { username, password } = req.body;
  let sql = 'select * from test where username=?';
  let sqlArr = [username];
  let result = await dbConfig.sySqlConnect(sql, sqlArr);
  if (result.length) {
    if (password === result[0].password) {
      const { id, username } = result[0];
      //Encrypt the token and respond to the client (parameter 1: value transmission rule; parameter 2: encryption rule; parameter 3: definition time)
      const token = jwt.sign({ id, username }, secret, { expiresIn: 60 * 60 });
      res.status(200).send({ msg: 'Login successful', token: token, status: 200 });
    } else {
      res.status(200).send({ msg: 'Login failed', status: 422 });
    }
  } else {
    res.status(200).send({ msg: 'Username does not exist', status: 401 })
  }
}

// Verify identity middleware module.exports = {
  token,
  login
}

③: Configure in app.js

//Write after app.use() and before routing app.use('/users/loginjwt', token.login); //Login interface (no need to verify token, so write before token middleware)
app.use(token.token);

4. Case implementation token

4.1 Principle

To ensure that the identity is unique and valid: each time a user sends a login request and logs in successfully, the server will respond to the user with an encrypted token (string) containing user information (unique). At this time, the user receives the token and stores it in sessionStorage or localStorage (here). At the same time, every time the user sends another request, the local token is carried in the request header. The server-side token verification middleware intercepts the request, decrypts the token, obtains the user information and compares it with the database. If the information exists, it is released (authentication success).

4.2 Effect Preview

4.3 Start implementing

Write simple static pages and implement ajax requests

login.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="../javascripts/jquery.min.js"></script>
  <title>Document</title>
</head>

<body>
  <form id="loginform">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Login">
  </form>
  <script>
    $(function() {
      $('#loginform').on('submit', function() {
        const formdata = $(this).serialize()
        $.ajax({
          url: '/users/loginjwt',
          type: 'post',
          data: formdata,
          success(res) {
            if (res.status === 200) {
              window.sessionStorage.setItem('token', res.token);
              location.href = '/user/index.html'
            }
          }
        })
        return false
      })
    })
  </script>
</body>
</html>

index.html

<script>
  if (!sessionStorage.getItem('token')) {
    location.href = '/user/login.html'
  }
</script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="../javascripts/jquery.min.js"></script>
  <title>Document</title>
</head>

<body>
  <h1>welcome index</h1>
  <a href="javascript:;" rel="external nofollow" >Log out</a>
  <script>
    $(function() {
      $.ajaxSetup({
        // Triggered before sending the request beforeSend(xhr) {
          // Set a custom request header here xhr.setRequestHeader('authorization', sessionStorage.getItem('token'))
        }
      })
      $.ajax({
        url: '/users',
        success(res) {
          console.log(res);
        }
      })
      $('a').on('click', function() {
        sessionStorage.clear();
        location.href = '/user/login.html'
      })
    })
  </script>
</body>
</html>

4.4 Notes

It is worth noting that the verification of the local token (whether it exists) must be written at the top of the page (to prevent the page from loading and sending the user list request again)
It is really annoying to add ajax request headers one by one. Here, the $ajaxSetup method is used to modify the default configuration of ajax. After configuration, all ajax requests written below it will have request headers.

This is the end of this article about how to use node scaffolding to build a server and implement token verification. For more relevant node token verification content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of how to implement Node login permission verification token verification
  • How to issue and verify token using jwt in node
  • Node implements token-based authentication
  • Node.js+captchapng+jsonwebtoken to implement login verification example

<<:  How to decompress multiple files using the unzip command in Linux

>>:  In-depth understanding of uid and gid in docker containers

Recommend

Parsing Linux source code epoll

Table of contents 1. Introduction 2. Simple epoll...

Introduction to Nginx regular expression related parameters and rules

Preface Recently, I have been helping clients con...

How to install Maven automatically in Linux continuous integration

Unzip the Maven package tar xf apache-maven-3.5.4...

How to add fields and comments to a table in sql

1. Add fields: alter table table name ADD field n...

【HTML element】Detailed explanation of tag text

1. Use basic text elements to mark up content Fir...

Simple encapsulation of axios and example code for use

Preface Recently, when I was building a project, ...

Detailed explanation of Angular parent-child component communication

Table of contents Overview 1. Overview of input a...

Vue+ElementUI implements paging function-mysql data

Table of contents 1. Problem 2. Solution 2.1 Pagi...

How to implement digital paging effect code and steps in CSS

A considerable number of websites use digital pagi...

Detailed explanation of common Docker commands

1. Help Command 1. View the current Docker versio...

CSS3 uses the transition property to achieve transition effects

Detailed description of properties The purpose of...

How to use the VS2022 remote debugging tool

Sometimes you need to debug remotely in a server ...

CSS realizes the realization of background image screen adaptation

When making a homepage such as a login page, you ...

JS implements the dragging and placeholder functions of elements

This blog post is about a difficulty encountered ...