问题描述
我目前正在使用node.js授权使用JSON Web令牌的用户,并使用EJS作为视图引擎进行表达。
I'm currently authorizing users with JSON web tokens using node.js and express with EJS as the view engine.
在我的server.js文件中使用简单的中间件:
Using simple middleware in my server.js file:
app.use(function(request, response, next){
var token = request.body.token || request.query.token || request.headers['x-access-token'];
console.log(request.body);
if(token){
jwt.verify(token, app.get('superSecret'), function(err, decoded){
if(err){
response.json({"message": "Failed to authenticate user"});
}
else{
request.decoded = decoded;
next();
}
});
}
else{
return response.status(403).json({"message":"No token was provided"});
}
});
及其下方的受保护路线,例如:
and protected routes below it e.g:
app.post('/userlist', function(request, response) {
response.json({some: json})
});
我无法理解或弄清楚如何保护GET路线,例如:
What I can't understand or figure out is how to protect a GET route such as:
app.get('/userprofile', function(request, response) {
response.render('pages/userprofile');
});
如果我直接通过某个网址提出请求 www.example.com/ userprofile
访问被拒绝,因为请求中不包含任何令牌。
If I make the request by some url directly www.example.com/userprofile
access is denied, as there is no token included with the request.
如果我通过ajax创建:
If I make it via ajax:
$.ajax({
type:"GET",
url:"https://www.example.com/userprofile",
headers:{"x-access-token": token },
success: function(result, success){
},
error: function (result, error){
}
});
未呈现响应但返回结果对象。我的电线在这里交叉了。
The response is not rendered but comes back in the result object. I've got my wires crossed somewhere here.
推荐答案
需要传递令牌才能使用。如果服务器无权访问它,则服务器无法对其进行验证。因此,您可以在路径中传递令牌:
A token needs to be passed in order to be used. If the server doesn't have access to it, the server can't validate it. So, you can pass the token in the path :
app.get('/userprofile/:token',function(request,response){
console.log(request.params.token);
});
在查询字符串中:
app.get('/userprofile',function(request,response){
console.log(request.query.token);
});
或作为cookie:
var cookieParser = require('cookie-parser');
app.use(cookieParser);
app.get('/userprofile',function(request,response){
console.log(request.cookies.token);
});
这篇关于使用JSON Web令牌和node.js / express保护URL的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!