我有一个使用JWT进行身份验证的Node.js后端服务器。当我发送登录请求并接收令牌时为应用程序构建前端时,我将其存储在浏览器的localStorage中,此后,我想重定向到仪表板,但是我面临的问题是,由于仪表板路由受到保护它需要令牌,但Js重定向方法不允许任何标头。那么,我应该如何解决这个问题呢?
const submit = document.getElementById("submit");
if (!localStorage.getItem("token"))
localStorage.setItem("token", "");
submit.addEventListener('click' , (e) => {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
e.preventDefault();
const data = {
email,
password
}
axios.post('/api/user/login', data)
.then((res) => {
document.getElementById('login_form').reset();
console.log(res.data);
if (res.data.success) {
localStorage.setItem("token", res.data.token);
document.window.location.href = '/organizer/dashboard';
}
})
.catch((err) => {
console.log(err);
})
});
成功登录请求后收到的JSON:
{
"success": true,
"token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViNTQzMWE1OTA0ZjkzMDQwOWM2OWU0NCIsIm5hbWUiOiJyYXNpayByYWoiLCJlbWFpbCI6ImZpc3J0QGdtYWlsLmNvbSIsImFjY190eXBlIjoib3JnYW5pc2VyIiwiaWF0IjoxNTMyMjQ4Mjc3LCJleHAiOjE1MzIyNTE4Nzd9.RHBMlVXXo-1YpwxnJbPdZ2VJ6Yt7aqTNJ3o6OzbXk4M"
}
答案 0 :(得分:1)
以下是自定义中间件及其用法的示例。
创建令牌并将其设置在cookie中:
function createAuthToken(id, agent, guidUser) {
var sign = config[env].signature;
var package = { 'device': id, 'access': 'authenticated', 'agent': agent, 'user': guidUser }
return jwt.sign(package, sign, { expiresIn: '90 days' });
};
app.post('/authenticate', function (req, res) {
var body = req.body;
var updatedToken = createAuthToken(body.device, body.userAgent, body.user);
var newDate = new Date();
var expDate = newDate.setMonth(newDate.getMonth() + 3)
res.cookie('id', updatedToken, { sameSite: true, maxAge: expDate });
res.send({ Success: true})
});
中间件(Nodejs):
function authenticateRoute(req, res, next) {
var token = req.cookies["id"];
var sign = config[env].signature;
jwt.verify(token, sign, function (err, decoded) {
if (err || !decoded) {
console.log("invalid token");
res.send(403);
}
else if (decoded && (!decoded.access || decoded.access == "unauthenticated")) {
console.log("unauthenticated token");
res.send(403);
}
else if (decoded && decoded.access == "authenticated") {
console.log("valid token")
next();
}
else {
console.log("something suspicious")
res.send(403);
}
});
};
然后在要使用此身份验证的所有路由上:
app.post('/authedcall', authenticateRoute, function (req, res) {
res.send({ Success: true })
});
app.post('/unauthedcall', function (req, res) {
res.send({ Success: true })
});
已认证的路线:
app.use('/loginroute', express.static(__dirname + "/login")); //no auth
app.use('/dashboard', authenticateRoute, express.static(__dirname + "/dash")); //auth route
答案 1 :(得分:0)
我认为您正在寻找这个。...
<Switch>
<PrivateRoute exact path="/dashboard" component={Dashboard} />
</Switch>
您可以将专用路由包装在switch中,然后将其经过验证的路径以及要加载的组件放进去
检查此内容将对您有所帮助 privateroute