如何在Angular中使用Node-Casbin?

问题描述

回答了有关Node-casbin库的问题。我想在前端的Angular中使用此库。不幸的是,我不知道该怎么做。我想将此库与字符串一起使用。因此,我想将策略和数据声明为字符串-而不是文件

  1. 使用的角度:10.0.0
  2. 使用的casbin版本:5.1.6

我所做的所有编码工作: 在package.json中,我添加了以下代码

  "browser": {
    "fs": false,"path": false,"os": false
  },

我将代码添加到服务中,例如:

  async loadEnforcer() {
    const enforcer = (await new Enforcer().initWithString(
      this.policy,this.dataSet
    )) as any;
    const sub = 'alice'; // the user that wants to access a resource.
    const obj = '/alice_data/'; // the resource that is going to be accessed.
    const act = 'GET'; // the operation that the user performs on the resource.

    console.log(enforcer);

    console.log(
      'the user permission is : ' + enforcer.getPermissionsForUser('alice')
    );

    if (enforcer.enforce(sub,obj,act) === true) {
      console.log('permit alice to read data1');
    } else {
      console.log('deny the request,show an error');
    }
  }

但是我仍然收到来自Angular的错误,例如:

core.js:4197 ERROR Error: Uncaught (in promise): TypeError: fs_1.readFileSync is not a function
TypeError: fs_1.readFileSync is not a function
    at Config.parse (config.js:64)
    at Function.newConfig (config.js:29)
    at Model.loadModel (model.js:109)
    at Object.newModel (model.js:291)
    at Enforcer.<anonymous> (enforcer.js:62)
    at Generator.next (<anonymous>)
    at enforcer.js:21
    at new ZoneAwarePromise (zone-evergreen.js:960)
    at push.../../node_modules/casbin/lib/enforcer.js.__awaiter (enforcer.js:17)
    at Enforcer.initWithAdapter (enforcer.js:61)
    at resolvePromise (zone-evergreen.js:798)
    at zone-evergreen.js:705
    at rejected (tslib.es6.js:72)
    at ZoneDelegate.invoke (zone-evergreen.js:364)
    at Object.onInvoke (core.js:27437)
    at ZoneDelegate.invoke (zone-evergreen.js:363)
    at Zone.run (zone-evergreen.js:123)
    at zone-evergreen.js:857
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:27425)

我尝试以与那里https://github.com/kowthalganesh/casbin-angular/blob/master/src/app/app.component.ts相同的方式进行操作-但仍然收到错误消息。

您能帮我吗? 非常感谢!

解决方法

永远不要在客户端包含这样的逻辑。除了浏览器中没有文件系统(库似乎依赖于该文件系统)之外,在前端中包含此类内容也是一个高度安全的问题。

如果您确实需要在应用程序中包含此类功能,则应仅将其放在后端。