Loopback 4:CRUDRestController 的授权装饰 - 无论如何可能吗?

Posted

技术标签:

【中文标题】Loopback 4:CRUDRestController 的授权装饰 - 无论如何可能吗?【英文标题】:Loopback 4: Authorization decoration of CRUDRestController - is it in anyway possible? 【发布时间】:2021-10-28 20:22:50 【问题描述】:

想知道社区中是否有人对如何使用有任何经验或指导 CrudRestController 端点上的授权装饰器(或任何自定义装饰?)(https://loopback.io/doc/en/lb4/Decorators_authorize.html)? (https://loopback.io/doc/en/lb4/Creating-crud-rest-apis.html)。

查看了crud-rest.controller.ts 的源代码,似乎没有办法真正做到这一点。

似乎很难在 CrudRestController 中使用任何端点装饰而不采取非常hacky的方法和/或批量复制crud-rest.controller.ts中的代码,而且我们基本上必须为每个模型编写每个端点手工。

也许有人提出了一些建议或对方法有一些指导?到目前为止,使用授权组件和 CrudRestController 的身份验证是使用授权函数的唯一方法 (https://loopback.io/doc/en/lb4/Authorization-component-authorizer.html)

【问题讨论】:

【参考方案1】:

似乎其中一部分在于:

https://github.com/loopbackio/loopback4-example-shopping/blob/9188104c01516a5cbd4ce13f28abe18bafef821e/packages/shopping/src/services/basic.authorizor.ts

 /**
   * Allow access only to model owners, using route as source of truth
   *
   * eg. @post('/users/userId/orders', ...) returns `userId` as args[0]
   */
  if (currentUser[securityId] === authorizationCtx.invocationContext.args[0]) 
    return AuthorizationDecision.ALLOW;
  

所以我最终做了:

async authorize(
      context: AuthorizationContext,
      metadata: AuthorizationMetadata,
    ) 
        const parent = context.invocationContext?.parent
        const request = parent?.getBinding("rest.http.request").getValue(parent)
        const givenUserId = request?.body?.userId

        // next line finds out the user id in the JWT payload
        const jwtUserId = context?.principals[0]?.payload?.sub
        if (!jwtUserId || (givenUserId && givenUserId != jwtUserId)) 
            return AuthorizationDecision.DENY;
         else 
            return AuthorizationDecision.ALLOW;
        
    

因为我的 userId 在 http 参数中提供(发布表单或获取参数)

我还使用自定义 JTWService 来读取有效负载并使其在 UserProfile 中可用。

这可能不是最好的方法,但到目前为止它确实有效。我仍在研究如何处理读取请求,并使用装饰器通过 userId 对所有请求添加过滤器,如果没有更好的结果,我将在此处发布我的发现。

【讨论】:

以上是关于Loopback 4:CRUDRestController 的授权装饰 - 无论如何可能吗?的主要内容,如果未能解决你的问题,请参考以下文章

Loopback 4 调试器 nodemon 解决方案

Loopback-4 通过模型添加时间戳 createdAt 和 updatedAt

Loopback 4:CRUDRestController 的授权装饰 - 无论如何可能吗?

LoopBack 4 基于 Node 的 TS 建造 API 与微服务

在 LoopBack 4 中访问 express 应用以添加中间件

在 Loopback 4 中创建一个模拟请求对象