当前位置:网站首页>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});
}
})
});
这样就实现简单的使用了~
边栏推荐
- 面试官:MySQL 中 update 更新,数据与原数据相同时会执行吗?大部分人答不上来!
- [Cloud Native] 4.2 DevOps Lectures
- STC8H Development (15): GPIO Drives Ci24R1 Wireless Module
- OpenMLDB + Jupyter Notebook:快速搭建机器学习应用
- TF generates uniformly distributed tensor
- Easyui 表单验证「建议收藏」
- SecureCRT sets the timeout period for automatic disconnection
- Swift 需求 如何防止把view重复添加到win里面
- 6 rules to sanitize your code
- Kubernetes Service对象
猜你喜欢

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

好未来,想成为第二个新东方

Arcgis工具箱无法使用,显示“XML包含错误“的解决方法

Activiti7审批流

Shanghai Konan SmartRocket series product introduction (3): SmartRocket iVerifier computer interlocking system verification tool

Install win virtual machine on VMware
![[Implementation of the interface for adding, deleting, checking, and modifying a double-linked list]](/img/49/ebedcd4d27aa608360ac17e504f36d.png)
[Implementation of the interface for adding, deleting, checking, and modifying a double-linked list]

CVPR22 Oral | shunt through multi-scale token polymerization from attention, code is open source

APP自动化测试框架-UiAutomator2基础入门

十步以内,用小程序快速生成App!
随机推荐
Cookie, session, token
xctf攻防世界 Web高手进阶区 shrine
深度剖析 Apache EventMesh 云原生分布式事件驱动架构
Use zeros(), ones(), fill() methods to generate data in TF
2022 首期线下 Workshop!面向应用开发者们的数据应用体验日来了 | TiDB Workshop Day
2.1.5 大纲显示问题
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Activiti7审批流
Under the NVM node installation;The node environment variable configuration
4D Summary: 38 Knowledge Points of Distributed Systems
leetcode 刷题日记 计算右侧小于当前元素的个数
mysql 找不到或无法加载已注册的 .Net Framework Data Provider。
Flask入门学习教程
Leetcode 93 复原IP地址
Solution: Edu Codeforces 109 (div2)
Chatting embarrassing scenes, have you encountered it?Teach you to get the Doutu emoticon package with one click, and become a chat expert
TF uses constant to generate data
5个 Istio 访问外部服务流量控制最常用的例子,你知道几个?
Synchronization lock synchronized traces the source
Xiaohei's leetcode journey: 94. Inorder traversal of binary trees (supplementary Morris inorder traversal)