【发布时间】:2021-01-03 08:31:16
【问题描述】:
我已经做了一个快速后端,并想使用 JsonWebToken npm 库添加一些安全性。
在 react 应用中,我使用拦截器在每个请求上设置身份验证令牌:
Axios.interceptors.request.use(function (config) {
const token = localStorage.getItem("api_token") || "auth_pending";
config.headers.Authorization = token;
console.log("Injected header token",token);
return config;
});
在我的节点后端,我使用 express 库为除登录之外的所有请求设置了一个中间件。
app.use(/\/((?!login).)*/, (req, res, next)=>{
const {authorization} = req.headers;
// console.log(authorization); next(); #If end function here the token is shown in the console.
jwt.verify(authorization, '53CR37C0D3', function(err, decoded) {
if(err){
console.error(err);
return res.status(403).send("Token is not valid.");
}
req.duser = decoded.user;
res.status(200).send("Access granted.");
next();
});
});
如代码所示,如果我只使用中间件来记录令牌,它就可以正常工作。但如果我想使用 JWT 对其进行解码,授权将变为 undefined。 我认为这与 cors 预检请求有关,但我无法弄清楚。
【问题讨论】:
标签: node.js reactjs express axios http-headers