在loopback4中,我创建了自定义身份验证和授权处理程序,并将其连接到应用程序中。但是,如果身份验证功能返回UserProfile
对象并跳过对undefined
用户的授权,则授权处理程序称为only。
无论身份验证的结果如何,我都希望每次都调用我的授权处理程序。我想允许未经身份验证的呼叫(不认识用户)仍然流经授权处理程序,以使其根据最终用户的身份以外的其他因素来判断是否允许该呼叫。
如何使每次调用授权处理程序?
export class MySequence implements SequenceHandler { constructor( @inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute, @inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams, @inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod, @inject(SequenceActions.SEND) public send: Send, @inject(SequenceActions.REJECT) public reject: Reject, @inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn, ) {} // see: https://loopback.io/doc/en/lb4/Loopback-component-authentication.html#adding-an-authentication-action-to-a-custom-sequence async handle(context: RequestContext) { try { const {request, response} = context; const route = this.findRoute(request); //call authentication action console.log(`request path = ${request.path}`); await this.authenticateRequest(request); // HOW DO I CONTROL AUTHORIZATION CALL THAT FOLLOWS? // Authentication step done, proceed to invoke controller const args = await this.parseParams(request, route); const result = await this.invoke(route, args); this.send(response, result); } catch (error) { if ( error.code === AUTHENTICATION_STRATEGY_NOT_FOUND || error.code === USER_PROFILE_NOT_FOUND ) { Object.assign(error, {statusCode: 401 /* Unauthorized */}); } this.reject(context, error); } } }
完整的代码示例很长,因此我将其发布了in a gist here。
在loopback4中,我创建了自定义身份验证和授权处理程序,并将其连接到应用程序中。但是,仅当身份验证函数返回...
我发现了一种为每个请求调用授权处理程序的方法。仍然感觉不太正确,因此可能有更好的解决方案。