HapiJs路线上的角色访问基础

编程入门 行业动态 更新时间:2024-10-09 14:18:02

HapiJs<a href=https://www.elefans.com/category/jswz/34/1771416.html style=路线上的角色访问基础"/>

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路线上的角色访问基础

本文发布于:2024-05-06 17:39:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路线   角色   基础   HapiJs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!