当前位置:网站首页>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});
}
})
});
这样就实现简单的使用了~
边栏推荐
- Usage of placeholder function in Tensorflow
- 开发者必备:一文快速熟记【数据库系统】和【软件开发模型】常用知识点
- openGauss数据库基本操作(超详细)
- Blender程序化建模简明教程【PCG】
- APP automation test framework - UiAutomator2 introductory
- Pagoda measurement - building LightPicture open source map bed system
- In-depth analysis of Apache EventMesh cloud-native distributed event-driven architecture
- Basic JSON usage
- BulkInsert方法实现批量导入
- Synchronization lock synchronized traces the source
猜你喜欢
随机推荐
Arcgis工具箱无法使用,显示“XML包含错误“的解决方法
6 rules to sanitize your code
从源码方面来分析Fragment管理中 Add() 方法
聊聊SQL语句中 DDL 、DML 、DQL 、DCL 分别是什么
abstract class or interface
级联下拉菜单的实现「建议收藏」
leetcode 38. 外观数列
Technology Sharing | How to Handle Header Cookies in Interface Automation Testing
L3-2 Delete up to three characters (30 points)
Use zeros(), ones(), fill() methods to generate data in TF
ACM MM 2022 | Cloud2Sketch: Painting with clouds in the sky, AI brush strokes
1215 – Cannot add foreign key constraint
Quotefancy ,提供鼓舞人心语录的壁纸网站 - 倾城之链
Chatting embarrassing scenes, have you encountered it?Teach you to get the Doutu emoticon package with one click, and become a chat expert
mysql 找不到或无法加载已注册的 .Net Framework Data Provider。
聊天尬死名场面,你遇到过吗?教你一键获取斗图表情包,晋升聊天达人
JS Deobfuscation - AST Restoration Case
FileZilla搭建FTP服务器图解教程
Leetcode 93 IP addresses
APP automation test framework - UiAutomator2 introductory