路线上的角色访问基础"/>
HapiJs路线上的角色访问基础
我现在用的是HapiJs在服务器端,并希望做角色路由配置的基础上,我想限制用户访问某些终点
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 8000 });
server.route({
method: 'GET',
path: 'api1',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: 'api2',
handler: function (request, reply) {
reply('Hello');
}
});
server.route({
method: 'GET',
path: 'api3',
handler: function (request, reply) {
reply('Hello');
}
});
const parseHeader = (request, h) => {
const { role } = JSON.parse(request.headers["roles"]);
};
server.ext("onRequest", parseHeader);
server.start(function () {
console.log('Server running at:', server.info.uri);
});
在这里我得到了角色,从角色的头所以角色可以是“管理”或“客户”。如果角色是管理员用户可以访问所有API端点“API1”,“API2”和“API3”,但如果它的“客户”,那么只有“API3”可能是入店。
如何实现这种航线上的授权?
回答如下:您需要创建“中间件” - 前处理程序,将检查用户的角色,如果用户的角色是admin,然后继续否则拒绝访问
var Boom = require('boom');
const CheckAdmin= function (request, reply) {
const { role } = JSON.parse(request.headers["roles"]);
if(role=='admin'){
return reply.continue();
}else{
return reply(Boom.unauthorized('Access Denied'));
}
}
server.route({
method: 'GET',
path: 'api1',
config: {
pre: [{ method: CheckAdmin }],
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: 'api2',
config: {
pre: [{ method: CheckAdmin }],
handler: function (request, reply) {
reply('Hello, world!');
}
});
// API3是开放的,所有可以使用,所以没必要在这里补充预处理器
server.route({
method: 'GET',
path: 'api3',
handler: function (request, reply) {
reply('Hello');
}
});
更多推荐
HapiJs路线上的角色访问基础
发布评论