Zum Hauptinhalt springen

Frontend-Nutzung

Casbin.js is a Casbin addon that facilitates your access-control management in the frontend application.

Installation

npm install casbin.js
npm install casbin

oder

yarn add casbin.js

Frontend Middlewares

MiddlewareTypAutorBeschreibung
reakt-authzReagierenCasbinReagiere Wrapper für Casbin.js
rbac-ReaktionReagieren@daobengRollenbasierte Zugriffskontrolle in React mit HOCs, CASL und Casbin.js
vue-authzVueCasbinVue wrapper für Casbin.js
angular-authzWinkelCasbinWinkelwickeln für Casbin.js

Schnellstart

You can use the manual mode in your frontend application and set the permissions whenever you wish.

const casbinjs = require("casbin. s");
// Benutzerberechtigung:
// Er/Sie kann `data1` und `data2` Objekte lesen und `data1` Objekt schreiben
const permission = {
"read": ["data1", "data2"],
"write": ["data1"]
}

// Casbin ausführen. s im manuellen Modus, was erfordert, dass Sie die Berechtigung manuell festlegen.
const authorizer = new casbinjs.Authorizer("manual");

Now we have an authorizer, authorizer. We can get permission rules from it by using the authorizer.can() and authorizer.cannot() APIs. Die Rückgabewerte dieser 2 APIs sind JavaScript-Versprechen (Details hier), also sollten wir die then() Methode des Rückgabewertes wie folgt verwenden:

result = authorizer.can("write", "data1");
Ergebnis. hen(Erfolg, fehlgeschlagen) => {
if (success) {
console. og("Sie können data1");
} else {
console. og("Sie können Daten nicht schreiben1");
}
});
// Ausgabe: Sie können Daten 1 schreiben

The cannot() API is used in the same way:

result = authorizer.cannot("read", "data2");
Ergebnis. hen(Erfolg, fehlgeschlagen) => {
if (success) {
console. og("Sie können nicht data2");
} else {
console. og("Sie können data2");
}
});
// Ausgabe: Sie können data2 lesen

In the code above, the success variable in the parameters means the request gets the result without throwing an error and doesn't mean that the permission rule is true. The failed variable is also unrelated to the permission rules. Das macht nur Sinn, wenn im Antragsprozess etwas schief läuft.

You can refer to our React example to see a practical usage of Casbin.js.

Permission Object

Casbin.js will accept a JSON object to manipulate the corresponding permission of a visitor. For example:

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

The permission object above shows that the visitor can read the data1 and data2 objects, while they can only write the data1 objects.

Erweiterte Nutzung

Casbin.js provides a perfect solution for integrating your frontend access-control management with your backend Casbin service.

Use the auto mode and specify your endpoint when initializing the Casbin.js Authorizer, it will automatically sync the permission and manipulate the frontend status.

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 wird die Berechtigung automatisch mit Ihrem Backend Casbin Service synchronisieren.
authorizer.setUser("Tom");

// Berechtigung auswerten
result = authorizer.can("read", "data1");
Ergebnis. Sie(Erfolgreich fehlgeschlagen) => {
if (success) {
// Einige Frontend-Prozeduren ...
}
});

Entsprechend müssen Sie eine Schnittstelle (z.B. eine RestAPI), um das Berechtigungsobjekt zu generieren und an das Frontend zu übergeben. Rufen Sie in Ihrem API-Controller CasbinJsGetUserPermission auf, um das Berechtigungsobjekt zu erstellen. Hier ist ein Beispiel in Beego:

note

Dein Endpunkt-Server sollte so etwas wie

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

// Controller
func (c *APIController) GetFrontendPermission() {
// Besucher von den GET-Parametern holen. (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, the CasbinJsGetPermissionForUser API is only supported in Go Casbin and Node-Casbin. If you want this API to be supported in other languages, please raise an issue or leave a comment below.

API-Liste

setPermission(permission: string)

Berechtigungsobjekt festlegen. Immer im manuellen Modus verwendet.

setUser(user: string)

Legen Sie die Besucheridentität fest und aktualisieren Sie die Berechtigung. Immer im Auto- Modus verwendet.

can(action: string, object: string)

Prüfen Sie, ob der Benutzer Aktion auf Objekt ausführen kann.

cannot(action: string, object: string)

Check if the user cannot perform action on object.

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

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

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

Prüfen Sie, ob der Benutzer Aktion auf eines der Objekte ausführen kann.

Warum Casbin.js

People may wonder about the difference between Node-Casbin and Casbin.js. In a word, Node-Casbin is the core of Casbin implemented in the NodeJS environment, and it's normally used as an access-controlling management toolkit at the server ends. Casbin.js is a frontend library that helps you use Casbin to authorize your webpage users at the client side.

Normalerweise es ist nicht angemessen, direkt einen Casbin-Dienst aufzubauen und die Autorisierung/Vollstreckungsaufgaben an einer Web-Frontend-Anwendung zu erledigen, da folgende Probleme auftreten:

  1. When someone turns on the client, the enforcer will be initialized, and it will pull all the policies from the backend persistent layers. Eine hohe Koncurrenz könnte die Datenbanken stark unter Druck setzen und einen hohen Netzwerkdurchsatz kosten.
  2. Loading all policies to the client side could bring security risks.
  3. It is difficult to separate the client and server as well as facilitate agile development.

We need a tool that eases the process of using Casbin at the frontend. Actually, the core of Casbin.js is the manipulation of the current user's permission at the client side. Wie Sie bereits erwähnt haben, holt Casbin.js einen bestimmten Endpunkt. Diese Prozedur wird die Berechtigung des Benutzers mit dem Backend Casbin Service synchronisieren. After having the permission data, developers can use Casbin.js interfaces to manage the behavior of the user at the frontend side.

Casbin.js avoids the two problems mentioned above: Casbin service will no longer be pulled up repeatedly, and the size of passing messages between the client and the server is reduced. We also avoid storing all the policies at the frontend. The user can only access their own permission, but has no knowledge about the access-control model and other users' permissions. Außerdem kann Casbin.js auch den Client und den Server im Autorisierungsmanagement effizient entkoppeln.