Skip to main content

RBAC Authorization

Custom Policy Example

Zuplo is extensible, so we don't have a built-in policy for RBAC Authorization, instead we have a template here that shows you how you can use your superpower (code) to achieve your goals. To learn more about custom policies see the documentation.

RBAC policies can be built many ways depending on your requirements. This example shows how to perform a simple check of whether or not the current user is a member of a set of allowed roles.

Example Custom Policy

The code below is an example of how this custom policy module could be implemented.

modules/rbac-policy-inbound.ts
import { HttpProblems, ZuploContext, ZuploRequest } from "@zuplo/runtime";

interface PolicyOptions {
allowedRoles: string[];
}

export default async function (
request: ZuploRequest,
context: ZuploContext,
options: PolicyOptions,
policyName: string,
) {
// Check that an authenticated user is set
// NOTE: This policy requires an authentication policy to run before
if (!request.user) {
context.log.error(
"User is not authenticated. A authorization policy must come before the RBAC policy.",
);
return HttpProblems.unauthorized(request, context);
}

// Check that the user has roles
if (!request.user.data.roles) {
context.log.error("The user is not assigned any roles.");
return HttpProblems.unauthorized(request, context);
}

// Check that the user has one of the allowed roles
if (
!options.allowedRoles.some(
(allowedRole) => request.user?.data.roles.includes(allowedRole),
)
) {
context.log.error(
`The user '${request.user.sub}' is not authorized to perform this action.`,
);
return HttpProblems.forbidden(request, context);
}

// If they made it here, they are authorized
return request;
}

Configuration

The example below shows how to configure a custom code policy in the 'policies.json' document that utilizes the above example policy code.

config/policies.json
{
"name": "my-rbac-policy-inbound-policy",
"policyType": "rbac-policy-inbound",
"handler": {
"export": "default",
"module": "$import(./modules/YOUR_MODULE)",
"options": {
"allowedRoles": [
"admin",
"editor"
]
}
}
}
  • name the name of your policy instance. This is used as a reference in your routes.
  • policyType the identifier of the policy. This is used by the Zuplo UI. Value should be rbac-policy-inbound.
  • handler/export The name of the exported type. Value should be default.
  • handler/module the module containing the policy. Value should be $import(./modules/YOUR_MODULE).
  • handler/options The options for this policy:
    • allowedRoles

      The roles allowed to access the resource

Read more about how policies work