Javascript 如何在客户端Node.js中实现JSON web令牌
我正在使用JWT验证Node.js express应用程序来访问我的管理页面。我和邮递员测试了我的路线,效果很好,问题出在客户端。我将简化我的代码和问题,使问题变得非常简单 我的问题是,在使用Javascript 如何在客户端Node.js中实现JSON web令牌,javascript,node.js,express,jwt,Javascript,Node.js,Express,Jwt,我正在使用JWT验证Node.js express应用程序来访问我的管理页面。我和邮递员测试了我的路线,效果很好,问题出在客户端。我将简化我的代码和问题,使问题变得非常简单 我的问题是,在使用localStorage本地存储令牌后,如何将重定向到我的管理页面 我已经尝试使用ajax解决这个问题,但是页面还是一样的。我还尝试了window.location='/admin',但在这一次中,我无法发送包含令牌的标题 首先,我的服务器端: app.get('/admin', verifyToken,
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中那样在头中发送令牌并自动重定向,有什么方法吗?非常感谢。如果您的管理页面呈现为完整页面,那么只需在/admin ajax请求成功处理程序中执行document.write(result)
success : function(result) {
document.write(result)
}
如果您与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.");
}
});
}
我注意到使用这种方法不是一种好的做法。在我的示例中,在客户端进行重定向并不好,最好是在服务器端进行重定向,而不仅仅是使用本地存储的不太安全的方法来存储令牌 因此,我告诉自己为什么不在服务器端执行重定向,为此,我使用
cookie解析器
中间件检查创建的cookie是否包含我的令牌,如果是真的,则重定向到admin页面
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.");
}
})
谢谢,这是一个很好的解决方案,但是URL仍然是相同的
/admin/login
,当页面重定向到/admin
时,您有没有办法自动更改它?