当前位置:网站首页>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});
}
})
});
这样就实现简单的使用了~
边栏推荐
- 【微服务~Nacos】Nacos之配置中心
- Evolution of MLOps
- Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
- 你的 Link Button 能让用户选择新页面打开吗?
- 肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
- TRUNCATE表之后空间未释放
- JS Deobfuscation - AST Restoration Case
- Several ways to draw timeline diagrams
- 基于ABP的AppUser对象扩展
- 【GORM】模型关系-HasMany关系
猜你喜欢

Flask introductory learning tutorial

How to Make Your Company Content GDPR Compliant
Quotefancy ,提供鼓舞人心语录的壁纸网站 - 倾城之链

2022年中国第三方证券APP创新专题分析

shell学习

Multiple reasons for MySQL slow query

力扣 1413. 逐步求和得到正数的最小值

Kubernetes Service对象

孙正义亏掉1500亿:当初投贵了

In-depth analysis of Apache EventMesh cloud-native distributed event-driven architecture
随机推荐
【EF】 更新条目时出错。有关详细信息,请参见内部异常。[通俗易懂]
BulkInsert方法实现批量导入
This article lets you quickly understand implicit type conversion [integral promotion]!
MySQL——JDBC
xctf攻防世界 Web高手进阶区 shrine
跨端技术方案选什么好?
Metasploit常用命令、技术功能模块
小程序+自定义插件的关键性
Interpretation of the paper (DropEdge) "DropEdge: Towards Deep Graph Convolutional Networks on Node Classification"
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
abstract class or interface
十步以内,用小程序快速生成App!
Evolution of MLOps
TF generates uniformly distributed tensor
OKR 锦囊妙计
AI识万物:从0搭建和部署手语识别系统
Cookie, session, token
STC8H Development (15): GPIO Drives Ci24R1 Wireless Module
random.normal() and random.truncated_normal() in TF
leetcode 39. 组合总和(完全背包问题)