当前位置:网站首页>NodeJS使用JWT
NodeJS使用JWT
2022-08-09 21:54:00 【碰磕】
JWT(jsonwebtoken)
目前最流行的跨域身份验证解决方案
在nodejs中使用
安装
npm install jsonwebtoken --save
使用
- 1.在路由中引入
var jwt = require('jsonwebtoken');
- 2.定义一个密钥
const secret = 'nidemiyao'//用于加密
- 3.定义生成token的函数
//生成token
//info也就是payload是需要存入token的信息
function createToken(info) {
let token = jwt.sign(info, secret, {
//Token有效时间 单位s
expiresIn:60 * 60*24
})
return token
}
- 4.定义验证token的函数
//验证Token
function verifyToken(token) {
console.log(token)
return new Promise((resolve, reject) => {
jwt.verify(token, secret, (error, result) => {
if(error){
reject(error)
} else {
resolve(result)
}
})
})
}
- 5.可以设置白名单
定义一下
//白名单
const whiteList = ['/manage/login']
- 6.使用
路由名.use((req,res,next) => {
if(!whiteList.includes(req.url)) {
//判断请求头是否携带正确的token
verifyToken(req.headers.authorization).then(res => {
next()
}).catch(e => {
res.status(401).send('403')//验证失败返回什么
})
} else {
next()
}
})
场景
常用于登录
通过创建密钥返回给前台,前台进行一个本地保存,再在封装请求中添加该请求头token…即可实现加密!!!
//登陆
路由名.post("/manage/login",(req,res)=>{
let {
user}=req.body;
let sql=`select *from admin where uname='${user.username}' and upassword='${user.password}'`;
conn.query(sql,(err,result,fields)=>{
if(err){
return "失败";
}
console.log(result)
if(result.length!==0){
let token =createToken(user)
res.send({
"result":result,"token":token});
}else{
res.send({
"result":result});
}
})
});
这样就实现简单的使用了~
边栏推荐
- xctf攻防世界 Web高手进阶区 shrine
- 电脑系统重装后怎么用打印机扫描出文件?
- AI Knows Everything: Building and Deploying a Sign Language Recognition System from Zero
- TRUNCATE表之后空间未释放
- Blender程序化建模简明教程【PCG】
- SecureCRT background color
- NIO Cup 2022 Nioke Summer Multi-School Training Camp 7 CFGJ
- AI识万物:从0搭建和部署手语识别系统
- 肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
- 论文解读(DropEdge)《DropEdge: Towards Deep Graph Convolutional Networks on Node Classification》
猜你喜欢

你真的了解乐观锁和悲观锁吗?

MLOps的演进历程

Five Star Holdings Wang Jianguo: Deepen the track with "plant spirit" and promote growth with "animal spirit"

宝塔实测-搭建LightPicture开源图床系统

APP automation test framework - UiAutomator2 introductory

Blender程序化建模简明教程【PCG】

Kubernetes Service对象

JSON 基本使用

Activiti7审批流

阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
随机推荐
你的 Link Button 能让用户选择新页面打开吗?
js array object deduplication
Simple questions peek into mathematics
2.1.5 大纲显示问题
Leetcode 93 IP addresses
The round functions in the np, ceil function and floor function
AI+Medical: Using Neural Networks for Medical Image Recognition and Analysis
Xiaohei leetcode's refreshing rainy day trip, just finished eating Yufei Beef Noodles, Mala Tang and Beer: 112. Path Sum
用户代码未处理MetadataException
Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
Chatting embarrassing scenes, have you encountered it?Teach you to get the Doutu emoticon package with one click, and become a chat expert
Converting angles to radians
为什么这么多人都想当产品经理?
你真的了解乐观锁和悲观锁吗?
Several ways to draw timeline diagrams
MySQL——JDBC
腾讯继续挥舞降本增效“大刀”,外包员工免费餐饮福利被砍了
台风生成,广州公交站场积极开展台风防御安全隐患排查
NIO Cup 2022 Nioke Summer Multi-School Training Camp 7 CFGJ
Arcgis工具箱无法使用,显示“XML包含错误“的解决方法