当前位置:网站首页>Node generates and verifies tokens (typescript syntax)
Node generates and verifies tokens (typescript syntax)
2022-07-22 18:34:00 【Agwenbi】
1、 First installation jsonwebtoken
(c)npm install jsonwebtoken -S
2、 According to the login information sent by the front end , Generate corresponding token
import { Router,Request,Response } from "express";
import jwt from 'jsonwebtoken';
export default (router:Router) => {
router.post('/',(req:Request,res:Response) => {
/*
req.body Encrypted token Information here is {user:admin,pass:admin}
'Agwenbi' Encrypted key , Make an appointment with yourself
expiresIn Expiration time , Unit second
*/
const token = jwt.sign({
...req.body
},'Agwenbi',{
expiresIn: (60 * 60 * 24) * 7//7 Days
});
res.status(200).json({//token Send the information to the front end
code:0,
msg:' The request is successful ',
token
});
});
return router;
}
// The front end receives token And save token Information
localStorage.setItem('xmds-token',loginResult.token);
3、 The front-end request header is added by default token Information
import axios,{AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import qs from 'qs';
class CreateAxios {
public http:AxiosInstance
constructor(){
this.http = axios.create({
timeout:10 * 1000,
baseURL:'http://localhost:8090'
});
}
}
class AxiosReq extends CreateAxios {// Request interceptor
constructor(){
super();
this.axiosReq();
}
axiosReq(){
this.http.interceptors.request.use((config:AxiosRequestConfig) => {
const token = localStorage.getItem('xmds-token');
if(token){// There is token, Default plus token
config.headers.common['Authorization'] = token;
}
if(config.method === 'post'){
config.data = qs.stringify(config.data);
}
return config;
},error => {
console.log(error);
})
}
}
class AxiosRes extends AxiosReq {// Response interceptors
constructor(){
super();
this.axiosRes();
}
axiosRes(){
this.http.interceptors.response.use((response:AxiosResponse<any>) => {
const result = Promise.resolve(response.data);
return result;
},error => {
console.log(error);
})
}
}
const http:AxiosInstance = new AxiosRes().http;
export default http;
4、node Global routing , verification token
import jwt from 'jsonwebtoken';
const noTokenUrl = ['/login'];// No validation required token Request
app.use((req:Request,res:Response,next:NextFunction) => {
const token = req.headers.authorization;
if(token){// There is token
jwt.verify(token,'Agwenbi',(error,decoded) => {//Agwenbi Indicates the key , Refer to the key set in step 2
const tokenFlag = error?.name;
if(tokenFlag === 'TokenExpiredError'){//token Be overdue
res.status(200).json({
code:401,
msg:'token Be overdue '
});
}else if(tokenFlag === 'JsonWebTokenError'){//token Validation failed
res.status(200).json({
code:401,
msg:' Invalid token'
});
}else{//token Not expired , And the verification passed
next();
}
});
}else{// non-existent token
if(noTokenUrl.includes(req.url)){// Whether it is unnecessary token Under the verified route
next();
}else{// Not in the accepted route , And not carried token
res.status(200).json({
code:401,
msg:' Invalid token'
});
}
}
});
边栏推荐
- 「武汉理工大学 软件工程复习」第五章 | 软件体系结构
- The MySQL password is correct, but the startup error is unable to create initial connections of pool Access denied for user ‘root‘@‘localhost
- Rocky basic exercise -shell SCRIPT-1
- How to build a clear and understandable data Kanban?
- es6赋值解构
- 2022-07-21:给定一个字符串str,和一个正数k, 你可以随意的划分str成多个子串, 目的是找到在某一种划分方案中,有尽可能多的回文子串,长度>=k,
- Hblock revitalizes the enterprise storage market
- Fabric. JS centered element
- 2021-10-18 burn bare board program with EOP
- 小程序CMS动态处理数据之内容模型和内容集合的使用
猜你喜欢
Using pypyodbc in Ubuntu cannot connect to SQL Server
43. String multiplication
化繁为简,聊一聊复制状态机系统架构抽象
It took two hours to find the bug about scrollto scrolling the distance from offsettop to the top
小程序CMS动态处理数据之内容模型和内容集合的使用
Fcntl function
Lesson 12 MySQL high availability component MHA
double类型不能进行精确计算的问题
"Review of software engineering in Wuhan University of technology" Chapter 1 | overview of software engineering
A trick to teach you how to visualize recruitment data ~ is there anyone who can't analyze these data cases?
随机推荐
Female guest registration
Applet implementation list and details page
水博士
[标准规范] 低代码的概念和定义到底是什么?无代码是否属于低代码?
「武汉理工大学 软件工程复习」第七章 | 软件测试
Simplify the complexity and talk about the abstraction of replication state machine system architecture
Understand relevant concepts of prosody. XMPP, jabber, bosh, etc
Inscription des femmes
debug glance(by quqi99)
关于STemwin中,外部实体按键操作Spinbox控件(fishing_2)
请教下,oracle-cdc是不是不支持检查点,当实时采集过程中任务挂了到重启这段时间的数据变化是不
Shell script uses expect automatic interactive login to remote host for batch shutdown
pm的报警告:“npm WARN config global --global, --local are deprecated
力扣解法汇总1089-复写零
SQL多条件查询无法实现
qt5.12 + vs2019 无法定位程序输入点 于动态链接库
反射+注解+泛型
Vim编辑器常用快捷方式
Mutexes and semaphores
三、泛型