我在服务器端使用sailsjs框架,在前端使用angularjs来构建SPA并使用jsonwebtoken进行令牌身份验证。我的用户api有以下信息:name:string,email:email,admin:Boolean,这是我用来生成令牌并发送到前端的信息,保存在localstorage中。 我的问题是:如果用户是我服务器端的管理员,我怎么做才能验证(检查令牌是否已经准备就绪并且一切正常)?
提前谢谢。
低于我目前检查服务器端令牌的政策
module.exports = function(req, res, next) {
var token;
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length == 2) {
var scheme = parts[0],
credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
token = credentials;
}
} else {
return res.json(401, {
err: 'Format is Authorization: Bearer [token]'
});
}
} else if (req.param('token')) {
token = req.param('token');
// We delete the token from param to not mess with blueprints
delete req.query.token;
} else {
return res.json(401, {
err: 'No Authorization header was found'
});
}
sailsTokenAuth.verifyToken(token, function(err, token) {
if (err) {
console.log('ERR estou em tokenauth policies');
return res.json(401, {
err: 'The token is not valid'
});
}
req.token = token;
next();
});
};
答案 0 :(得分:2)
执行3项政策:
SetJwt :`req。
sailsTokenAuth.verifyToken(token, function(err, token) {
if (err) {
console.log('ERR estou em tokenauth policies');
return res.json(401, {
err: 'The token is not valid'
});
} else req.token = token
}
<强> isAdmin 强>:
if (req.auth === ADMIN_LEVEL) next()
else res.forbidden()
<强> isUser 强>:
if (req.auth === USER_LEVEL) next()
else res.forbidden()
您的政策:
someControllerMethod: [setJwt, isAdmin]
当然,您需要在数据库中添加int
甚至标记isadmin
才能生效。令牌需要保存这些信息!