Introduction to JWTWhat is JWT The full name is The { "Name": "Zhang San", "Role": "Administrator", "Expiration time": "July 1, 2018 00:00" } Why do we need JWT? Let's first look at the general authentication process, based on 1. The user sends his username and password to the server. 2. After the server verification is passed, relevant data such as user role, login time, etc. are saved in the current 3. The server returns a 4. Each subsequent request by the user will pass 5. The server receives But there is a big problem here. If it is a server cluster, session data sharing is required and each server can read the session. The cost of this implementation is relatively high. JWT Data Structure The three parts of { "alg": "HS256", "typ": "JWT" }
Of course, you can also customize private fields. But be aware that JWT is unencrypted by default and can be read by anyone, so don't put secret information in this part. HMACSHA256 base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) After calculating the signature, the three parts of Security of JWT
Node simple demo - implementation of Koa JWT After talking about theoretical knowledge, let's take a look at how to implement First, after the user logs in, the server generates and returns Here we use jsonwebtoken, can generate Koa-jwt middleware further encapsulates Quickly build a koa project I found that there is currently no official way to quickly build a Install npm install -g koa-generator Start the project Open Generate Token For the convenience of demonstration, I directly define the variable const crypto = require("crypto"), jwt = require("jsonwebtoken"); // TODO: Use database // This should be stored in a database, but it is just for demonstration let userList = []; class UserController { // User login static async login(ctx) { const data = ctx.request.body; if (!data.name || !data.password) { return ctx.body = { code: "000002", message: "Invalid parameter" } } const result = userList.find(item => item.name === data.name && item.password === crypto.createHash('md5').update(data.password).digest('hex')) if (result) { const token = jwt.sign( { name: result.name }, "Gopal_token", // secret { expiresIn: 60 * 60 } // 60 * 60 seconds ); return ctx.body = { code: "0", message: "Login successful", data: { token } }; } else { return ctx.body = { code: "000002", message: "Incorrect username or password" }; } } } module.exports = UserController; Generate a Client obtains token After the front-end logs in and obtains login() { this.$axios .post("/api/login", { ...this.ruleForm, }) .then(res => { if (res.code === "0") { this.$message.success('Login successful'); localStorage.setItem("token", res.data.token); this.$router.push("/"); } else { this.$message(res.message); } }); } Encapsulate // axios request interceptor processes request data axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); config.headers.common['Authorization'] = 'Bearer ' + token; // Note the Authorization here return config; }) Verify token Using // Error handling app.use((ctx, next) => { return next().catch((err) => { if (err.status === 401) { ctx.status = 401; ctx.body = 'Protected resource, use Authorization header to get access\n'; }else{ throw err; } }) }) // Note: put it before the route app.use(koajwt({ secret: 'Gopal_token' }).unless({ // Configure whitelist path: [/\/api\/register/, /\/api\/login/] })) // routes app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) It is important to note the following points:
Demo If you directly access an interface that requires login, Register first, then log in, otherwise it will prompt that the username or password is wrong After logging in, bring Summarize This article summarizes the knowledge related to Due to the length of the article, I have the opportunity to talk about the source code of This article refer toJSON Web Token Getting Started Tutorial Node.js application: Koa2 uses JWT for authentication This is the end of this article about how to use koa2 in Node to implement a simple JWT authentication method. For more relevant Node koa2 JWT authentication content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Trash-Cli: Command-line Recycle Bin Tool on Linux
>>: MySQL 5.7.17 installation and configuration method graphic tutorial under Windows 10
This article shares the specific code of the firs...
This article shares the specific code of jquery+A...
This article example shares the specific code of ...
Environment Preparation Docker environment MySQL ...
This article example shares the specific code of ...
The parent node of the parent node, for example, t...
Table of contents Purpose npm init and package.js...
Pull the image # docker pull codercom/code-server...
Table of contents 1. Introduction 2. Usage 3. Dev...
Table of contents 1. Control the display and hidi...
Create a project directory mkdir php Create the f...
introduction Xiao A was writing code, and DBA Xia...
Preface: Integer is one of the most commonly used...
Today I would like to share with you the CSS3 tra...
Look at the code first #/bin/sh datename=$(date +...