Skip to content

[Question]How to add RBAC with domains in loopback4 #412

Open
@PoyuLU

Description

@PoyuLU
export class CasbinAuthorizationProvider implements Provider {
constructor(
@Inject('casbin.enforcer.factory')
private enforcerFactory: (name: string) => Promise<casbin.Enforcer>,
) {}

/**

@returns authenticateFn
*/
value(): Authorizer {
return this.authorize.bind(this);
}
async authorize(
authorizationCtx: AuthorizationContext,
metadata: AuthorizationMetadata,
): Promise {
const subject = this.getUserId(authorizationCtx.principals[0].id);
const resourceId = await authorizationCtx.invocationContext.get(
RESOURCE_ID,
{optional: true},
);
const object = resourceId ?? metadata.resource ?? authorizationCtx.resource;
const request: AuthorizationRequest = {
subject,
object,
action: metadata.scopes?.[0] ?? DEFAULT_SCOPE,
};

const allowedRoles = metadata.allowedRoles;

if (!allowedRoles) return AuthorizationDecision.ALLOW;
if (allowedRoles.length < 1) return AuthorizationDecision.DENY;

let allow = false;

// An optimization for ONLY searching among the allowed roles' policies
for (const role of allowedRoles) {
  const enforcer = await this.enforcerFactory(role);

  const allowedByRole = await enforcer.enforce(
    request.subject,
    request.object,
    request.action,
  );

  debug(`authorizer role: ${role}, result: ${allowedByRole}`);
  if (allowedByRole) {
    allow = true;
    break;
  }
}

debug('final result: ', allow);

if (allow) return AuthorizationDecision.ALLOW;
else if (allow === false) return AuthorizationDecision.DENY;
return AuthorizationDecision.ABSTAIN;
}

how to add domain in casbin.authorizer?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions