Перейти к основному содержанию

Открытые API Casbin

Введение

Допустим, что фронтенд вашего приложения получил access_token залогиненного пользователя и теперь хочет аутентифицировать пользователя для некоторого доступа. Вы не можете просто поместить access_token в заголовок HTTP-запроса для использования этих API, потому что Casdoor использует поле Authorization для проверки разрешения доступа. Как и любые другие API, предоставляемые Casdoor, поле Authorization состоит из идентификатора клиента приложения и секрета, используя Схему базовой HTTP-аутентификации. Это выглядит как Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>. По этой причине API Casbin должны вызываться сервером бэкенда приложения. Вот шаги, как это сделать.

Возьмем для примера приложение app-vue-python-example на демонстрационном сайте, заголовок авторизации должен быть: Authorization: Basic 294b09fbc17f95daf2fe dd8982f7046ccba1bbd7851d5c1ece4e52bf039d.

  1. Фронтенд передает access_token на сервер бэкенда через заголовок HTTP-запроса.
  2. Сервер бэкенда извлекает идентификатор пользователя из access_token.

Как предварительное примечание, эти интерфейсы также разработаны (на данный момент) для модели (sub, obj, act). Тело является форматом запроса, определенным моделью Casbin разрешений, обычно представляющим sub, obj и act соответственно.

В дополнение к API-интерфейсу для запроса применения контроля разрешений, Casdoor также предоставляет другие интерфейсы, которые помогают внешним приложениям получать информацию о политике разрешений, которая также перечислена здесь.

Применить

The Enforce API supports multiple query parameters to specify which permission(s) to enforce against. Only one parameter should be provided at a time:

  • permissionId: The identity of a specific permission policy (format: organization name/permission name)
  • modelId: The identity of a permission model (format: organization name/model name) - enforces against all permissions using this model
  • resourceId: The identity of a resource - enforces against all permissions for this resource
  • enforcerId: The identity of a specific enforcer
  • owner: The organization name - enforces against all permissions in this organization

Request using permissionId:

curl --location --request POST 'http://localhost:8000/api/enforce?permissionId=example-org/example-permission' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>' \
--data-raw '["example-org/example-user", "example-resource", "example-action"]'

Request using modelId:

curl --location --request POST 'http://localhost:8000/api/enforce?modelId=example-org/example-model' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>' \
--data-raw '["example-org/example-user", "example-resource", "example-action"]'

Request using resourceId:

curl --location --request POST 'http://localhost:8000/api/enforce?resourceId=example-org/example-resource' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>' \
--data-raw '["example-org/example-user", "example-resource", "example-action"]'

Response:

{
"status": "ok",
"msg": "",
"sub": "",
"name": "",
"data": [
true
],
"data2": [
"example-org/example-model/example-adapter"
]
}

Note: When using modelId, resourceId, enforcerId, or owner parameters, the response data array may contain multiple boolean values (one for each permission that was checked), and data2 contains the corresponding model and adapter identifiers.

BatchEnforce

The BatchEnforce API supports multiple query parameters to specify which permission(s) to enforce against. Only one parameter should be provided at a time:

  • permissionId: The identity of a specific permission policy (format: organization name/permission name)
  • modelId: The identity of a permission model (format: organization name/model name) - enforces against all permissions using this model
  • enforcerId: The identity of a specific enforcer
  • owner: The organization name - enforces against all permissions in this organization

Request using permissionId:

curl --location --request POST 'http://localhost:8000/api/batch-enforce?permissionId=example-org/example-permission' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>' \
--data-raw '[["example-org/example-user", "example-resource", "example-action"], ["example-org/example-user2", "example-resource", "example-action"], ["example-org/example-user3", "example-resource", "example-action"]]'

Request using modelId:

curl --location --request POST 'http://localhost:8000/api/batch-enforce?modelId=example-org/example-model' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>' \
--data-raw '[["example-org/example-user", "example-resource", "example-action"], ["example-org/example-user2", "example-resource", "example-action"]]'

Ответ:

{
"status": "ok",
"msg": "",
"sub": "",
"name": "",
"data": [
[
true,
true,
false
]
],
"data2": [
"example-org/example-model/example-adapter"
]
}

Note: When using modelId, enforcerId, or owner parameters, the response data array may contain multiple arrays of boolean values (one array for each permission that was checked), and data2 contains the corresponding model and adapter identifiers.

GetAllObjects

This API retrieves all objects (resources) that a user has access to. It accepts an optional userId parameter. If not provided, it uses the logged-in user's session.

Request with userId parameter:

curl --location --request GET 'http://localhost:8000/api/get-all-objects?userId=example-org/example-user' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Request using session (userId determined from session):

curl --location --request GET 'http://localhost:8000/api/get-all-objects' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Ответ:

{
"status": "ok",
"msg": "",
"data": [
"app-built-in",
"example-resource"
]
}

GetAllActions

This API retrieves all actions that a user can perform. It accepts an optional userId parameter. If not provided, it uses the logged-in user's session.

Request with userId parameter:

curl --location --request GET 'http://localhost:8000/api/get-all-actions?userId=example-org/example-user' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Request using session (userId determined from session):

curl --location --request GET 'http://localhost:8000/api/get-all-actions' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Ответ:

{
"status": "ok",
"msg": "",
"data": [
"read",
"write",
"admin"
]
}

GetAllRoles

This API retrieves all roles assigned to a user. It accepts an optional userId parameter. If not provided, it uses the logged-in user's session.

Request with userId parameter:

curl --location --request GET 'http://localhost:8000/api/get-all-roles?userId=example-org/example-user' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Request using session (userId determined from session):

curl --location --request GET 'http://localhost:8000/api/get-all-roles' \
--header 'Authorization: Basic <Your_Application_ClientId> <Your_Application_ClientSecret>'

Ответ:

{
"status": "ok",
"msg": "",
"data": [
"role_kcx66l"
]
}