我正在使用 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.");
}
});
}
那么如何在标题中发送令牌,就像我在客户端的Postman中一样,并自动重定向,有什么方法吗?非常感谢。
答案 0 :(得分:1)
如果您的管理页面呈现为完整页面,那么只需在/ admin ajax请求成功处理程序中执行document.write(result)
{{1}}
答案 1 :(得分:0)
如果您使用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.");
}
});
}
答案 2 :(得分:0)
我注意到使用这种方法不是一个好习惯。在我的示例中,在客户端进行重定向并不好,最好这样做服务器端,而不是使用 localStorage 的不太安全的方法来存储我的令牌
所以我告诉自己为什么不在我的服务器端进行重定向,为此我使用cookie-parser
中间件检查创建的cookie是否包含我的令牌,如果是,则重定向到管理页面。
Cookie或localStorage都不安全,但Cookie是存储我的令牌的好选择,因为网络存储在传输过程中不会强制执行任何安全标准,无论是使用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.");
}
})