node.js - 无法将 JWT 分配给标头请求
问题描述
我在使用 JWT 时遇到问题。在负责登录页面的路由器中,在发布请求中,我为每个登录用户分配了一个 JWT,尽管我无法在每个页面请求的标头中发送令牌,也无法将令牌实际保存在标头中。当我在每次登录后控制台记录令牌并将其复制粘贴到 POSTMAN 的标题时,它工作正常,因此我认为这是我的问题;
// generate a jwt for the login user
const token = jwt.sign({_id: this._id, isAdmin: this.isAdmin}, process.env.TOKEN_SECRET,
{expiresIn: 1800});
// send back to the homepage with the token in the header (?)
res.header('auth-token', token).redirect('/');
console.log(token);
在这个分配之后,我试图访问一个经过身份验证的用户页面,但它没有工作,我想是因为我提到的原因。
这是我的身份验证中间件,负责我添加到路由器的身份验证:
const jwt = require('jsonwebtoken');
module.exports = function(req, res, next) {
const token = req.header('auth-token');
if(!token){
console.log('Access denied. No token provided.');
return res.status(401).redirect('/login');
}
try{
const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
console.log(decoded);
req.user = decoded;
console.log('Access approved.');
next();
}
catch(ex){
console.log('Invalid token');
res.status(403).redirect('/');
}
}
我不知道我错过了什么。试图找到解决方案,但对我没有任何帮助。感谢帮助者!
解决方案
推荐阅读
- swift - Swift 应用程序在第二次调用时终止
- rtos - Zephyr RTOS 中的 sys_trace_void() 和 sys_trace_end_call() 函数调用有什么作用?
- google-apps-script - Google 表格/文档 - 表格自定义 - 条带
- graphql - 如何从 graphql 端点获取所有结果?
- java - 将数据插入实时数据库不起作用
- python - 在运行时从 Popen 对象的标准输出中读取
- python - 如何使用 python 集成下拉列表以选择带有数据透视表数据的条形图中的系列?
- node.js - 如何创建自托管的本地 React 应用程序?
- javascript - 验证码不会自动显示并在单击刷新时闪烁。不知道该怎么做
- python - 从 df.loc[] 获取新的 DF 并选择唯一值