Jac*_*ack 14 javascript node.js hapijs
我正在开发一个用HapiJS编写的rest API第一个项目.在登录过程之后,用户获得一个令牌以传递每个请求的标头.用户具有不同的角色(管理员,标准,访客,合作伙伴),并且只有具有特定角色的用户才能访问某些Api端点.有人可以帮助我以一种很好的方式定义这个检查,所以不必每次都在路线内写支票?
Mat*_*son 24
领域
你可以scopes
在hapi中使用.通过检查标头验证请求时,可以设置scope
用户凭据的属性:
var validateFunc = function (username, password, callback) {
... // Your logic here
return callback(null, true, {scope: 'admin'});
};
Run Code Online (Sandbox Code Playgroud)
定义路径时,您可以scopes
在config.auth.scope
属性中设置允许该端点的路径:
server.route({
...
config: {
auth: {
strategy: 'simple',
scope: ['user', 'admin']
},
}
...
});
Run Code Online (Sandbox Code Playgroud)
现在,只有经过身份验证user
或用户身份验证的用户admin
才能访问该路由.
处理
scope
用户的凭据config.auth.scope
允许访问它的任何人来配置您的路由可运行的例子
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 4000 });
server.register(require('hapi-auth-basic'), function (err) {
if(err) {
throw err;
}
server.auth.strategy('simple', 'basic', {
validateFunc: function (username, password, callback) {
if (username === 'admin') {
return callback(null, true, {scope: 'admin'}); // They're an `admin`
}
if (username === 'user') {
return callback(null, true, {scope: 'user'}); // They're a `user`
}
return callback(null, false);
}
});
server.route([{
config: {
auth: {
strategy: 'simple',
scope: ['admin'] // Only admin
},
},
method: 'GET',
path: '/admin',
handler: function(request, reply) {
reply('Admin page');
}
}, {
config: {
auth: {
strategy: 'simple',
scope: ['user', 'admin'] // user or admin
},
},
method: 'GET',
path: '/user',
handler: function(request, reply) {
reply('User page');
}
}
]);
server.start(function () {
console.log('Started server');
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4705 次 |
最近记录: |