node+token implements verification
This time I will bring you node token verification. What are the precautions for node token verification? 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.Traditional session cookie authentication
Because 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:- When making the first request, the user sends the account number and password
- If the background verification passes, a time-sensitive token will be generated, and then this token will be sent to the user.
- After the user obtains the token, Store this token locally, usually in localstorage or cookie
- . 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.
- 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.
- Can avoid CSRF attacks
- 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.
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]; }); });
store.set('loginedtoken',token);//store为插件
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); })
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(); } });
- Open the command line tool, enter openssl, and open openssl;
- Generate private key: genrsa -out rsa_private_key.pem 2048
- Generate public key: rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Click here to view the front-end code
code spliting optimization Vue packaging steps detailed explanation
Vue2 routing navigation and axios interceptor packaging
The above is the detailed content of node+token implements verification. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



We usually receive PDF files from the government or other agencies, some with digital signatures. After verifying the signature, we see the SignatureValid message and a green check mark. If the signature is not verified, the validity is unknown. Verifying signatures is important, let’s see how to do it in PDF. How to Verify Signatures in PDF Verifying signatures in PDF format makes it more trustworthy and the document more likely to be accepted. You can verify signatures in PDF documents in the following ways. Open the PDF in Adobe Reader Right-click the signature and select Show Signature Properties Click the Show Signer Certificate button Add the signature to the Trusted Certificates list from the Trust tab Click Verify Signature to complete the verification Let

1. After opening WeChat, click the search icon, enter WeChat team, and click the service below to enter. 2. After entering, click the self-service tool option in the lower left corner. 3. After clicking, in the options above, click the option of unblocking/appealing for auxiliary verification.

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

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 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.

PHP8 is the latest version of PHP, bringing more convenience and functionality to programmers. This version has a special focus on security and performance, and one of the noteworthy new features is the addition of verification and signing capabilities. In this article, we'll take a closer look at these new features and their uses. Verification and signing are very important security concepts in computer science. They are often used to ensure that the data transmitted is complete and authentic. Verification and signatures become even more important when dealing with online transactions and sensitive information because if someone is able to tamper with the data, it could potentially

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

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.
