Home Web Front-end JS Tutorial How to use node to implement token-based authentication

How to use node to implement token-based authentication

May 25, 2018 pm 02:50 PM
node based on accomplish

This time I will show you how to use node to implement token-based authentication, and what are the precautions for using node to implement token-based authentication. The following is a practical case, let's take a look.

Recently studied token-based authentication and integrated this mechanism into personal projects. Nowadays, the authentication method of many websites has shifted from the traditional seesion cookie to token verification. Compared with traditional verification methods, tokens do have better scalability and security.

Traditionalsession Cookie authentication

Since HTTP is stateless, it does not record the user's identity. After the user sends the account and password to the server, the background passes the verification, but the status is not recorded, so the next user's request still needs to verify the identity. In order to solve this problem, it is necessary to generate a record containing the user's identity on the server side, that is, session, and then send this record to the user and store it locally in the user's local area, that is, cookie. Next, the user's request will bring this cookie. If the client's cookie and the server's session can match, it means that the user's identity authentication has passed.

Token identity verification

The process is roughly as follows:

  1. When making the first request, the user sends the account number and password

  2. If the background verification passes, a time-sensitive token will be generated, and then this token will be sent to the user.

  3. After the user obtains the token, Store this token locally, usually in localstorage or cookie

  4. . Each subsequent request will add this token to the request header, and all interfaces that need to verify identity will be checked. Verify the token. If the data parsed by the token contains user identity information, the identity verification is passed.

Compared with traditional verification methods, token verification has the following advantages:

  1. In token-based authentication, the token is transmitted through the request header. Instead of storing authentication information in session or cookie. This means stateless. You can send requests to the server from any terminal that can send HTTP requests.

  2. Can avoid CSRF attacks

  3. When the session is read, written or deleted in the application, a file operation will occur in temp folder of the operating system, at least the first time. Assume there are multiple servers and the session is created on the first service. When you send the request again and the request lands on another server, the session information does not exist and you get an "unauthenticated" response. I know, you can solve this problem with a sticky session. However, in token-based authentication, this problem is naturally solved. There is no sticky session problem because the request token is intercepted on every request sent to the server.

The following is an introduction to using node jwt (jwt tutorial) to build a simple token identity verification

Example

When a user When logging in for the first time, submit the account and password to the server. If the server passes the verification, the corresponding token will be generated. The code is as follows:

const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
//生成token的方法
function generateToken(data){
  let created = Math.floor(Date.now() / 1000);
  let cert = fs.readFileSync(path.join(dirname, '../config/pri.pem'));//私钥
  let token = jwt.sign({
    data,
    exp: created + 3600 * 24
  }, cert, {algorithm: 'RS256'});
  return token;
}
//登录接口
router.post('/oa/login', async (ctx, next) => {
  let data = ctx.request.body;
  let {name, password} = data;
  let sql = 'SELECT uid FROM t_user WHERE name=? and password=? and is_delete=0', value = [name, md5(password)];
  await db.query(sql, value).then(res => {
    if (res && res.length > 0) {
      let val = res[0];
      let uid = val['uid'];
      let token = generateToken({uid});
      ctx.body = {
        ...Tips[0], data: {token}
      }
    } else {
      ctx.body = Tips[1006];
    }
  }).catch(e => {
    ctx.body = Tips[1002];
  });
});
Copy after login
The user will store the token obtained locally after passing the verification:

store.set('loginedtoken',token);//store为插件
Copy after login
After the client requests an interface that requires identity verification, the token will be placed in the request header and passed to the server:

service.interceptors.request.use(config => {
  let params = config.params || {};
  let loginedtoken = store.get('loginedtoken');
  let time = Date.now();
  let {headers} = config;
  headers = {...headers,loginedtoken};
  params = {...params,_:time};
  config = {...config,params,headers};
  return config;
}, error => {
  Promise.reject(error);
})
Copy after login
The server intercepts the token and verifies the legitimacy of all interfaces that require login. .

function verifyToken(token){
  let cert = fs.readFileSync(path.join(dirname, '../config/pub.pem'));//公钥
  try{
    let result = jwt.verify(token, cert, {algorithms: ['RS256']}) || {};
    let {exp = 0} = result,current = Math.floor(Date.now()/1000);
    if(current <= exp){
      res = result.data || {};
    }
  }catch(e){
  }
  return res;
}
app.use(async(ctx, next) => {
  let {url = ''} = ctx;
  if(url.indexOf('/user/') > -1){//需要校验登录态
    let header = ctx.request.header;
    let {loginedtoken} = header;
    if (loginedtoken) {
      let result = verifyToken(loginedtoken);
      let {uid} = result;
      if(uid){
        ctx.state = {uid};
        await next();
      }else{
        return ctx.body = Tips[1005];
      }
    } else {
      return ctx.body = Tips[1005];
    }
  }else{
    await next();
  }
});
Copy after login
The public key and private key used in this example can be generated by yourself. The operation is as follows:

  1. Open the command line tool, enter openssl, and open openssl;

  2. Generate private key: genrsa -out rsa_private_key.pem 2048

  3. Generate public key: rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps to use scss in Angular projects

How to use vue2.0 koa2 mongodb to achieve registration and login

The above is the detailed content of How to use node to implement token-based authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Use Java to write code to implement love animation Use Java to write code to implement love animation Dec 23, 2023 pm 12:09 PM

Realizing love animation effects through Java code In the field of programming, animation effects are very common and popular. Various animation effects can be achieved through Java code, one of which is the heart animation effect. This article will introduce how to use Java code to achieve this effect and give specific code examples. The key to realizing the heart animation effect is to draw the heart-shaped pattern and achieve the animation effect by changing the position and color of the heart shape. Here is the code for a simple example: importjavax.swing.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles