当前位置: 首页 > article >正文

jsonwebtoken生成token和解析

先上npm地址

jsonwebtoken:jsonwebtoken - npm

express-jwt:express-jwt - npmps

const express = require('express');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJWT} = require('express-jwt')

const app = express();

// 设置密钥
const secretKey = 'my_secret_key';

// 生成Token
const token = jwt.sign({ username: 'user123' }, secretKey, { expiresIn: '1h' });

// 验证Token1(在req.auth里获取解析值)
app.use(expressJWT({ 
    secret: config.jwtSecretKey, 
    algorithms:["HS256"],
    credentialsRequired: false,
    getToken: function fromHeaderOrQuerystring(req) {
        if ( req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer" ) {
            return req.headers.authorization.split(" ")[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    } 
}).unless({ path: ['/api/reguser','/api/login'] }))

//验证Token2
//(这里获取到的token值一定要是jwt生成的token,不能添加其他东西,否则会报incalid Token)
const router = express.Router()
function verifyToken(req, res, next) {
    const token = req.headers.authorization;
    
    if (!token) {
      return res.status(403).json({ code: -1, message: '请登录后再进行操作' });
    }
  
    jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
      if (err) {
        return res.status(500).json({ code: -1, message: 'token验证失败'+err });
      }
  
      req.user = decoded;
      next();
    });
}
router.get('/userinfo',verifyToken, (req, res) => {
  res.send(`Welcome ${req.user.username}!`);
});)


// 启动服务器
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

http://www.kler.cn/news/162684.html

相关文章:

  • 进制 + 原码,反码,补码
  • 供应链产品经理常用的ChatGPT通用提示词模板
  • 代立冬:基于Apache Doris+SeaTunnel 实现多源实时数据仓库解决方案探索实践
  • 持续集成交付CICD:CentOS 7 安装 Sonarqube9.6
  • 使用Java API操作HDFS
  • 云上巴蜀丨云轴科技ZStack成功实践精选(川渝)
  • Leetcode—2034.股票价格波动【中等】
  • 信息可视化在数字孪生中的应用:打造直观决策支持系统
  • css 十字分割线(含四等分布局)
  • Python-链式调用详解(默认参数,函数的嵌套调用、关键字传参)
  • xxl-job详解
  • RestTemplate硬编码的使用
  • C++STL的string模拟实现
  • 实现SQL server数据库完整性
  • 进程控制与原语
  • Termux+Hexo结合内网穿透轻松实现安卓手机搭建博客网站发布公网访问
  • 这把养生局~
  • Vue 子路由页面发消息给主路由页面 ,实现主页面显示子页面的信息
  • [架构之路-258]:目标系统 - 设计方法 - 软件工程 - 软件设计 - 架构设计 - 软件架构与软件框架的详细比较
  • 倒计时模块复习
  • 一篇文章带你快速入门 Vue 核心语法
  • chfs,简单好用的局域网共享网盘
  • 设计并实现一个多线程图书馆管理系统,涉及数据库操作
  • python圣诞树代码编程
  • HarmonyOS
  • JVM GUI可视化监控及诊断工具
  • Python语言基础知识(二)
  • 【S32DS报错】-2-提示Error while launching command:arm-none-eabi-gdb –version错误
  • DeepIn,UOS统信专业版安装运行Java,JavaFx程序
  • LeetCode-496. 下一个更大元素 I【栈 数组 哈希表 单调栈】