问题描述
问题 2:它们的用例是什么?
jwtMW:
const jwtMW = exjwt({
secret: "keyboard cat 4 ever",algorithms: ["HS256"],credentialsrequired: true,});
方法一
router.post("/authRequest",jwtMW,async (req,res) => {
let toeken = req.headers.authorization;
// use the decoded infomation for further verification
});
接近二
router.post("/authRequest2",res) => {
const reqToken = req.headers.authorization.split(" ")[1];
const secret = "keyboard cat 4 ever";
var decoded = jwt.verify(reqToken,secret);
// use the decoded infomation for further verification
});
提前致谢。
解决方法
第一种方法不正确,因为在路径中的路径之后您可以使用中间件,但 jwtMW
不是中间件,如果您想使用中间件,请尝试这样:
check-auth.js
const jwt = require('jsonwebtoken');
module.exports = (req,res,next) => {
try {
const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN'
if (!token) {
throw new Error('Authentication failed!');
}
const decodedToken = jwt.verify(token,'supersecret_dont_share');
req.userData = { userId: decodedToken.userId };
next();// it's important line
} catch (err) {
throw new Error('Authentication failed!');
}
};
之后在路由文件中需要中间件
const checkAuth = require('../middleware/check-auth');//it's a exmple
router.post('/authRequest',checkAuth,async (req,res) => {
// do somethings
});
在第二种方法中你不使用中间件