当前位置:网站首页>[node] scaffolding server to complete token verification
[node] scaffolding server to complete token verification
2022-06-22 09:20:00 【Jdoit CW】
Content
Use scaffolding to quickly build node project
use mysql The connection pool realizes the interaction with the database
use jsonwebtoken Realization token Authentication
Comprehensive case : Use the introduction login page to realize the above content
1. Quickly build node project
We all know express The framework can be developed efficiently node The server , But for the construction of the bottom layer, you have to rely on your own handwriting . However express-generator The emergence of has solved this problem well , It can generate the basic skeleton of the project for us with one click , a node The scaffold
1.1 Generating project
①: First, install it globally express : npm install express -g
②: Then global installation express-generator:npm install express-generator -g
③: Then use the command to create the project : express token_learn( Project name )
1.2 Modify entry file
For many people who are used to rolling up the server by hand ,app.js Always unforgettable , However, the entry file in this skeleton is www.js. At this point, we can manually modify app.js Code , Make it our portal 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 run 3000'))
2. Connect mysql database
Here, the connection pool is used for connection ( Efficient and safe )
2.1 Create connection
①: install mysql modular :npm i mysql
②: Configure the connection pool under the project root directory
First create... In the project root directory util Folder , Create under folder bdconfig.js file
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) => {
// use Promise Object to transform it , Easy to receive data
const pool = mysql.createPool(this.mysqlParams);
pool.getConnection((err, conn) => {
if (err) {
reject(err)
} else {
conn.query(sql, sqlArr, (err, data) => {
// Operating the database
if (err) {
reject(err)
} else {
resolve(data)
}
})
conn.release() // Release the connection
}
})
})
}
}
2.2 Use connections
You only need to pass in sql(sql sentence )、sqlArr( Parameters ), adopt Promise After the transformation, the result can be obtained directly with the return value
3. token Authentication
With web The development of ,session、cookie The disadvantages of the verification method are becoming more and more prominent , here token Give birth to ,token The power of is not limited to No state Of , Also because it can Cross domain
3.1 Implementation steps
①: First installation jsonwebtoken modular :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 ( Customize )
token = async(req, res, next) => {
// Definition token Verify middleware functions ( Apply to every request except login )
if (req.headers.authorization) {
const token = req.headers.authorization;
const {
id, username } = jwt.verify(token, secret); // Yes token Perform decryption search
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 login interface ( Because the request header does not carry token, So the quotation is in token Before verifying the 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];
// Yes token Encrypted responses to clients ( Parameters 1: Value transfer rules ; Parameters 2: Encryption rules ; Parameters 3: Defining time )
const token = jwt.sign({
id, username }, secret, {
expiresIn: 60 * 60 });
res.status(200).send({
msg: ' Landing successful ', token: token, status: 200 });
} else {
res.status(200).send({
msg: ' Login failed ', status: 422 });
}
} else {
res.status(200).send({
msg: ' The username does not exist ', status: 401 })
}
}
// Authentication middleware
module.exports = {
token,
login
}
③: stay app.js To configure
// Written in app.use() after , Before routing
app.use('/users/loginjwt', token.login); // Login interface ( No need to verify token, So it's written in token Before Middleware )
app.use(token.token);
4. Case realization token
4.1 Explain the principle
To ensure that the identity is unique and valid : Each time the user sends a login request and the login succeeds , The server will respond to the user with user information ( only ) The encryption token( character string ), At this time, the user receives token, And put token Stored in sessionStorage or localStorage in ( Here is ). At the same time, each time the user sends another request , Carry the local... In the request header token, Server side token Verify that the middleware intercepts the request , Yes token To decrypt , Get the user information and compare it with the database , Release if the information exists ( Authentication succeeded ).
4.2 Results the preview

4.3 Start implementation
Write simple static pages , And realize ajax request
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=" Sign in ">
</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:;"> Log out </a>
<script> $(function() {
$.ajaxSetup({
// Triggered before sending the request beforeSend(xhr) {
// Set the 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 Be careful
- It is worth noting that , about Local
tokenValidation of the ( Whether there is ) Be sure to write it at the top of the page ( Prevent page loading , Send the user list request again ) - about
ajax Request header, It's really annoying to add one by one , This is used here$ajaxSetupMethod , modify ajax Default configuration . After configuration , Written below ajax request , Will bring the request header .
For technical issues , Welcome to disturb ,
边栏推荐
猜你喜欢

Medical information management system database mysql

np. Arange and np Linspace nuances (data overflow problem)

DOM编程
![[tensorboard] step on all minefields and solve all your problems](/img/35/fc0f7ed311bf7c0321e1257ff6a1a6.png)
[tensorboard] step on all minefields and solve all your problems

Didi's two-sided summary

5 interview questions, grasp the underlying principle of string!

模板引擎,让交互变得优雅

为啥要使用梯度下降法

Common SQL statements in MySQL

文件小能手---multer
随机推荐
【node】脚手架搭建服务器,完成token验证
How C processes use non static methods
为啥要使用梯度下降法
Logistic regression and linear regression
Final典型案例
Common SQL statements in MySQL
C language question brushing | three item operation to realize capital judgment (16)
PHP output color image with specified height and width for web page background image
Classic & Cases
【node】快收下爬虫,我们不再为数据发愁
变量那些事
两个线程各执行100次i++,得到的可能值
进程状态汇总
Record some Oracle operation commands
rewrite? Reload? Are you dizzy?
IS_ ERR()
VMware installation Kali
Volumedetect of ffmpeg
Fuzzy query and aggregate function
炒股致富之curl抓股票信息