我正在使用 jwt 在Node.js Express应用程序上工作,以访问我的管理页面。我用Postman测试了我的路线,它运行良好,问题在客户方面。我将简化我的代码和问题,以使问题非常克莱尔。
我的问题是,在代币与localStorage
本地存储后,如何将重定向到我的管理页面?
我已经尝试用ajax
解决此问题,但是页面仍然相同。我也尝试了window.location='/admin'
,但是在此中,我无法发送包含令牌的标题。
首先是我的服务器端:
app.get('/admin', verifyToken, function(req, res, next) {
res.render('views/admin');
});
function verifyToken(req, res, next) {
var token = req.headers['access-token'];
if (!token)
return res.status(401).send({ auth: false, message: 'NO TOKEN PROVIDED' });
jwt.verify(token, config.secret_key, function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
console.log("Token is valid");
next();
});
}
客户端:
function login(event) {
event.preventDefault();
let formData = new FormData(event.target);
fetch("/admin/login", {
method: 'POST',
body: formData
}).then(function (response) {
return response.json();
}).then(function (result) {
if (result.auth === true) {
localStorage.token = result.token;
//HERE IS THE PROBLEM
$.ajax({
type : "GET",
url : "/admin",
beforeSend: function(xhr){
xhr.setRequestHeader('access-token', localStorage.token);
},
success : function(result) {
//HERE IS THE PROBLEM
window.location='/admin';
}
});
} else {
console.log("Incorrect username or password.");
}
});
}
那么,如何像我在客户端的邮递员中一样将标记发送到标题中并自动重定向,是否有任何方法?非常感谢。
如果您的管理页面作为完整页面渲染,则只需document.write.write(结果(in/admin ajax请求成功处理程序
success : function(result) {
document.write(result)
}
我注意到使用此方法不是一个好习惯。在我的示例中,将重定向在客户端不好,最好在服务器端中进行,而不是我使用 localStorage 使用较低的安全方法存储我的令牌。
所以我告诉自己为什么不在服务器端进行重定向,为此,我使用cookie-parser
中间件检查cookie创建的cookie是否包含我的令牌,如果是的,请进行重定向以进行管理页面。
cookie或localstorage都不安全,但是cookie是存储我令牌的一个不错选择,因为 Web Storage 在转移期间都不会执行任何安全标准,无论是使用HTTP还是HTTPS。
。我的服务器端
app.get('/admin', verifyToken, function(req, res,next) {
res.render('views/admin');
});
app.get('/admin/login', function(req, res){
if(req.cookies.myToken)//Make redirection
return res.redirect('/admin');
res.render('views/login');
});
function verifyToken(req, res, next) {
var token = req.cookies.myToken;
if (!token)
return res.status(401).send({ auth: false, message: 'No Token Provided!'});
jwt.verify(token, config.secret_key, function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
req.userId = decoded.id;
next();
});
}
客户端:
fetch("/admin/login", {
method: 'POST',
body: formData,
credentials: 'include',
}).then(function (response) {
return response.json();
}).then(function (result) {
console.log(result);
if (result.auth === true) {
window.location="/admin";
} else {
console.log("Incorrect username or password.");
}
})
如果您与JWT一起工作,则随着每个请求发送令牌。
通常,这将使用诸如jQuery或Angular之类的框架来完成,您使用中间件,将令牌添加到每个请求中。
在这里,jQuery的样本
$.ajaxPrefilter(function( options ) {
if (options.beforeSend) {
options.beforeSend = function (xhr) {
xhr.setRequestHeader('Authorization',
'Bearer'+localStorage.getItem('token'));
}
}
});
如果有的话,可以使用您的代码:
function login(event) {
event.preventDefault();
let formData = new FormData(event.target);
fetch("/admin/login", {
method: 'POST',
body: formData
}).then(function (response) {
return response.json();
}).then(function (result) {
if (result.auth === true) {
localStorage.token = result.token;
window.location='/admin';
}
});
} else {
console.log("Incorrect username or password.");
}
});
}