Использование интерфейса
Casbin.js is a Casbin addon that facilitates your access-control management in the frontend application.
Установка
npm install casbin.js
npm install casbin
или
yarn add casbin.js
Интерфейс
Среднее | Тип | Автор | Описание |
---|---|---|---|
react-authz | Реакция | Casbin | React оболочка для Casbin.js |
рбак-реакция | Реакция | @daobeng | Управление доступом на основе ролей в React с помощью HOC, CASL и Casbin.js |
vue-authz | Vue | Casbin | Оболочка Vue для Casbin.js |
углово-авторский | Угловой | Casbin | Угловая обертка для Casbin.js |
Быстрый старт
You can use the manual
mode in your frontend application and set the permissions whenever you wish.
const casbinjs = require("casbin". s");
// Установить права пользователя:
// Он может читать `data1` и `data2` объекты и может записать `data1` объект
const permission = {
"read": ["data1", "data2"],
"write": ["data1"]
}
// Запустить casbin. в ручном режиме, который требует установки разрешения вручную.
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. Возвращаемыми значениями этих 2 API являются Promises JavaScript (подробнее здесь), поэтому мы должны использовать метод then()
возвращаемого значения:
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()
API is used in the same way:
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
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. Это имеет смысл только когда что-то пойдет не так в процессе запроса.
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.
Расширенное использование
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 автоматически синхронизирует разрешение с вашим сервисом Casbin.
authorizer.setUser("Том");
// Оценка результатов
= authorizer.can("read", "data1");
результат. ru(успех, failed) => {
if (success) {
// Некоторая процедура интерфейса ...
}
});
Соответственно, вам нужно раскрыть интерфейс (например, RestAPI) для создания объекта разрешения и передачи его фронтенду. В вашем контроллере API вызовите CasbinJsGetUserPermission
для создания объекта разрешения. Вот пример в Биго:
::note
Ваш сервер конечной точки должен вернуть что-то вроде
{
"other":"other",
"data": "What you get from `CasbinJsGetPermissionForUser`"
}
:::
// Маршрутизатор
beego.Router("api/casbin", &controllers.APIController{}, "GET:GetFrontendPermission")
// Контроллер
func (c *APIController) GetFrontendPermission() {
// Получить посетителя с GET параметров. (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
setPermission(permission: string)
Задать разрешение объекта. Always used in manual
mode.
setUser(user: string)
Задайте идентификатор посетителя и обновите разрешение. Всегда используется в режиме auto
.
can(action: string, object: string)
Отметьте, если пользователь может выполнить действие
на объекте
.
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>)
Check if the user can perform action
on any one of the objects
.
Почему 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.
Обычно нецелесообразно непосредственно создавать службу Casbin и выполнять задачи по санкционированию/принудительной реализации на веб-интерфейсе из-за следующих проблем:
- When someone turns on the client, the enforcer will be initialized, and it will pull all the policies from the backend persistent layers. Высокое соотношение может привести к жесткому давлению на базы данных и стоимости большого количества пропускной способности сети.
- Loading all policies to the client side could bring security risks.
- 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. Как вы говорили, Casbin.js делает выборку из указанной конечной точки. Эта процедура будет синхронизировать разрешение пользователя с сервисом Casbin. 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. Кроме того, Casbin.js может эффективно разрезать клиента и сервера в управлении авторизацией.