[英]Role based authentication in HapiJS
I am working on a rest API first project written with HapiJS. 我正在开发一个用HapiJS编写的rest API第一个项目。 After the login process the user gets a token to pass in the header of every request.
在登录过程之后,用户获得一个令牌以传递每个请求的标头。 Users have different roles (admin, standard, guest, partners) and some Api endpoint are reachable only by users with a certain role.
用户具有不同的角色(管理员,标准,访客,合作伙伴),并且只有具有特定角色的用户才能访问某些Api端点。 Someone could help me in defining this check in a nice way, so without writing the check everytime inside the route?
有人可以帮助我以一种很好的方式定义这个检查,所以不必每次都在路线内写支票?
Scopes 领域
You can use scopes
in hapi. 您可以在hapi中使用
scopes
。 When you authenticate the request by checking the header, you can set the scope
property of the user's credentials: 通过检查标头验证请求时,可以设置用户凭据的
scope
属性:
var validateFunc = function (username, password, callback) {
... // Your logic here
return callback(null, true, {scope: 'admin'});
};
When defining a route you can set the scopes
which are permitted to that endpoint in the config.auth.scope
property: 定义路由时,您可以在
config.auth.scope
属性中设置允许该端点的scopes
:
server.route({
...
config: {
auth: {
strategy: 'simple',
scope: ['user', 'admin']
},
}
...
});
Now, only users who are authenticated with the scope of user
or admin
, will be able to access that route. 现在,只有通过
user
或admin
范围进行身份验证的user
才能访问该路由。
Process 处理
scope
on the user's credentials scope
config.auth.scope
to whomever is allowed to access it config.auth.scope
设置为允许访问它的任何人来配置您的路由 Runnable Example 可运行的例子
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');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.