Passer au contenu principal

Frontend Usage

Casbin.js is a Casbin extension that simplifies access control management in frontend applications.

Installation

npm install casbin.js
npm install casbin

ou

yarn add casbin.js

Frontend Frameworks

FrameworkTypeAuteurDescription
react-authzReactCasbinEnveloppe React pour Casbin.js
rbac-reactReact@daobengRole-Based Access Control in React using Higher-Order Components, CASL, and Casbin.js
vue-authzVueCasbinEnveloppe Vue pour Casbin.js
angular-authzAngularCasbinEnveloppe Angular pour Casbin.js

Démarrage rapide

Configure Casbin.js in manual mode to set permissions explicitly in your frontend application:

const casbinjs = require("casbin.js");
// Set the user's permission:
// He/She can read `data1` and `data2` objects and can write `data1` object
const permission = {
"read": ["data1", "data2"],
"write": ["data1"]
}

// Run casbin.js in manual mode, which requires you to set the permission manually.
const authorizer = new casbinjs.Authorizer("manual");

With an authorizer instance, you can check permissions using authorizer.can() and authorizer.cannot(). Both methods return JavaScript Promises (see MDN documentation), so use the then() method to handle results:

result = authorizer.can("write", "data1");
result.then((success, failed) => {
if (success) {
console.log("you can write data1");
} else {
console.log("you cannot write data1");
}
});
// output: you can write data1

The cannot() method works identically:

result = authorizer.cannot("read", "data2");
result.then((success, failed) => {
if (success) {
console.log("you cannot read data2");
} else {
console.log("you can read data2");
}
});
// output: you can read data2

The success parameter indicates that the query completed without errors—not that permission was granted. Similarly, failed relates to query errors, not permission denial.

See our React example for practical Casbin.js usage.

Objet de permission

Casbin.js uses a JSON object to represent visitor permissions. Par exemple :

{
"read": ["data1", "data2"],
"write": ["data1"]
}

This object indicates that the visitor can read both data1 and data2 objects but can only write to data1.

Utilisation avancée

Casbin.js provides seamless integration between frontend access control and your backend Casbin service.

Use auto mode and specify your backend endpoint when initializing the Casbin.js Authorizer. It will automatically synchronize permissions and manage frontend authorization state:

const casbinjs = require('casbin.js');

// Set your backend Casbin service URL
const authorizer = new casbinjs.Authorizer(
'auto', // mode
{endpoint: 'http://your_endpoint/api/casbin'}
);

// Set your visitor.
// Casbin.js will automatically sync the permission with your backend Casbin service.
authorizer.setUser("Tom");

// Evaluate the permission
result = authorizer.can("read", "data1");
result.then((success, failed) => {
if (success) {
// Some frontend procedure ...
}
});

On the backend, expose an endpoint (such as a REST API) that generates the permission object for the frontend. Dans votre contrôleur API, appelez CasbinJsGetUserPermission pour construire l'objet de permission. This Beego example demonstrates the pattern:

note

Your endpoint should return a response like:

{
"other":"other",
"data": "What you get from `CasbinJsGetPermissionForUser`"
}
// Router
beego.Router("api/casbin", &controllers.APIController{}, "GET:GetFrontendPermission")

// Controller
func (c *APIController) GetFrontendPermission() {
// Get the visitor from the GET parameters. (The key is "casbin_subject")
visitor := c.Input().Get("casbin_subject")
// `e` is an initialized instance of Casbin Enforcer
c.Data["perm"] = casbin.CasbinJsGetPermissionForUser(e, visitor)
// Pass the data to the frontend.
c.ServeJSON()
}
note

Currently, CasbinJsGetPermissionForUser is available only in Go Casbin and Node-Casbin. To request support in other languages, please open an issue or leave a comment below.

API Reference

setPermission(permission: string)

Sets the permission object. Used primarily in manual mode.

setUser(user: string)

Sets the visitor identity and refreshes permissions. Used primarily in auto mode.

can(action: string, object: string)

Checks if the user can perform action on object.

cannot(action: string, object: string)

Checks if the user cannot perform action on object.

canAll(action: string, objects: Array<object>)

Checks if the user can perform action on all objects in objects.

canAny(action: string, objects: Array<object>)

Checks if the user can perform action on any object in objects.

Pourquoi Casbin.js

People often wonder about the distinction between Node-Casbin and Casbin.js. Node-Casbin is Casbin's core implementation for Node.js environments, typically deployed at the server level for access control management. Casbin.js is a frontend library that helps you apply Casbin authorization logic at the client side for webpage users.

Directly building a Casbin service for frontend authorization presents several issues:

  1. When a client connects, the enforcer initializes and pulls all policies from backend storage. High concurrency can strain databases and consume significant network bandwidth.
  2. Exposing all policies to clients creates security vulnerabilities.
  3. Tight coupling between client and server complicates development and maintenance.

Casbin.js addresses these challenges by managing user permissions at the client level. The core functionality involves synchronizing the current user's permissions with the backend Casbin service through a fetch operation. Once permission data is retrieved, developers can use Casbin.js interfaces to control user behavior at the frontend.

This approach eliminates repeated enforcer initialization, reduces message size between client and server, and avoids exposing all policies at the frontend. Users access only their own permissions without knowledge of the access control model or other users' permissions. Additionally, Casbin.js effectively decouples client and server authorization logic.