Casbin

Casbin

  • ドキュメント
  • API
  • エディター
  • IDE プラグイン
  • Single Sign-On (SSO)
  • フォーラム
  • ヘルプ
  • ブログ
  • Pricing
  • Contact Sales
  • Languages icon日本語
    • English
    • 中文
    • 한국어
    • Русский
    • Français
    • Deutsch
    • 翻訳に協力する
  • GitHub

›基本

基本

  • 概要
  • はじめよう
  • 仕組み
  • チュートリアル

モデル

  • サポートされるモデル
  • モデルの構文
  • エフェクト
  • 関数
  • RBAC
  • RBAC with Pattern
  • ドメイン付きRBAC
  • Casbin RBAC v.s. RBAC96
  • ABAC
  • 優先モデル
  • スーパー管理者

ストレージ

  • モデル ストレージ
  • ポリシーストレージ
  • ポリシーサブセットの読み込み

拡張

  • Enforcers
  • アダプター
  • Watchers
  • 派遣者
  • ロールマネージャー
  • ミドルウェア
  • GraphQL Middlewares
  • Cloud Native Middlewares

API

  • API の概要
  • 管理API
  • RBAC API
  • Domains API による RBAC
  • RoleManager API
  • データ権限

高度な使い方

  • マルチスレッド
  • Benchmarks
  • パフォーマンス最適化
  • Kubernetes の承認
  • Envoyによるサービスメッシュの承認

管理

  • 管理者ポータル
  • カスビンサービス
  • ログとエラー処理
  • フロントエンドの使用法

エディター

  • オンラインエディター
  • IDE プラグイン

もっと見る

  • Adopters
  • コントリビューション
  • プライバシーポリシー
  • 利用規約
Translate

はじめよう

インストール

Go
Java
https://mvnrepository.com/artifact/org.casbin/jcasbin
Node.js
PHP
Python
.NET
Rust
Delphi
Lua
go get github.com/casbin/casbin/v2
<dependency>
<groupId>org.casbin</groupId>
<artifactId>jcasbin</artifactId>
<version>1.x.y</version>
</dependency>
# NPM
npm install casbin --save

# Yarn
yarn add casbin

composer.json でこのパッケージをrequireの対象とします。以下でパッケージをダウンロードします:

composer require casbin/casbin
pip install casbin
dotnet add package Casbin.NET
cargo install cargo-edit
cargo add casbin

// If you use async-std as async executor
cargo add async-std

// If you use tokio as async executor
cargo add tokio // make sure you activate its `macros` feature
luarocks install casbin  

エラーが発生した場合:/usr/local/lib/luarocks/rocksへの書き込み権限がない場合は、特権ユーザとして実行するか、--localを指定してローカルツリーを使用すると良いでしょう。 次のようにコマンドの後ろに --local を付けて修正できます。

luarocks install casbin  --local

Casbin Enforcerを作成する

Casbinは、アクセス制御モデルを設定するために設定ファイルを使用します。

model.conf と policy.csv の2つの設定ファイルがあります。 model.conf はアクセスモデルを保存し、 policy.csv は特定のユーザー権限設定を保存します。 Casbinの利用方法は非常に洗練されています。 基本的には、1つの主要となる構造体が必要となります。それが enforcer です。 この構造体を構築するとき、 model.conf と policy.csv がロードされます。

言い換えると、Casbin Enforcer を作成するには、 Model と Adapter を提供する必要があります。

Casbin には、 FileAdapter があります。詳細は Adapter を参照してください。

  • Modelファイルとデフォルトの FileAdapter を使用する:
Go
Java
Node.js
PHP
Python
.NET
Delphi
Rust
Lua
import "github.com/casbin/casbin/v2"

e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
import org.casbin.jcasbin.main.Enforcer;

Enforcer e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
import { newEnforcer } from 'casbin';

const e = await newEnforcer('path/to/model.conf', 'path/to/policy.csv');
require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
import casbin

e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv")
using NetCasbin; 

var e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
var
casbin: ICasbin;
begin
casbin := TCasbin.Create('path/to/model.conf', 'path/to/policy.csv');
...
end
use casbin::prelude::*;

// If you use async_td as async executor
#[cfg(feature = "runtime-async-std")]
#[async_std::main]
async fn main() -> Result<()> {
let mut e = Enforcer::new("path/to/model.conf", "path/to/policy.csv").await?;
Ok(())
}

// If you use tokio as async executor
#[cfg(feature = "runtime-tokio")]
#[tokio::main]
async fn main() -> Result<()> {
let mut e = Enforcer::new("path/to/model.conf", "path/to/policy.csv").await?;
Ok(())
}
local Enforcer = require("casbin")
local e = Enforcer:new("path/to/model.conf", "path/to/policy.csv") -- The Casbin Enforcer
  • 他のAdapterとともにModelテキストを使用する:
Go
Python
import (
"log"

"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
xormadapter "github.com/casbin/xorm-adapter/v2"
_ "github.com/go-sql-driver/mysql"
)

// Initialize a Xorm adapter with MySQL database.
a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/casbin")
if err != nil {
log.Fatalf("error: adapter: %s", err)
}

m, err := model.NewModelFromString(`
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
`
)
if err != nil {
log.Fatalf("error: model: %s", err)
}

e, err := casbin.NewEnforcer(m, a)
if err != nil {
log.Fatalf("error: enforcer: %s", err)
}
import casbin
import casbin_sqlalchemy_adapter


# Use SQLAlchemy Casbin adapter with SQLLite DB
adapter = casbin_sqlalchemy_adapter.Adapter('sqlite:///test.db')

# Create a config model policy
with open("rbac_example_model.conf", "w") as f:
f.write("""
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
"""
)

# Create enforcer from adapter and config policy
e = casbin.Enforcer('rbac_example_model.conf', adapter)

権限のチェックする

アクセスが発生する直前のコードにEnforcementフックを追加する:

Go
Java
Node.js
PHP
Python
.NET
Delphi
Rust
Lua
sub := "alice" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.

ok, err := e.Enforce(sub, obj, act)

if err != nil {
// handle err
}

if ok == true {
// permit alice to read data1
} else {
// deny the request, show an error
}

// You could use BatchEnforce() to enforce some requests in batches.
// This method returns a bool slice, and this slice's index corresponds to the row index of the two-dimensional array.
// e.g. results[0] is the result of {"alice", "data1", "read"}
results, err := e.BatchEnforce([][]interface{}{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"jack", "data3", "read"}})
String sub = "alice"; // the user that wants to access a resource.
String obj = "data1"; // the resource that is going to be accessed.
String act = "read"; // the operation that the user performs on the resource.

if (e.enforce(sub, obj, act) == true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
const sub = 'alice'; // the user that wants to access a resource.
const obj = 'data1'; // the resource that is going to be accessed.
const act = 'read'; // the operation that the user performs on the resource.

if ((await e.enforce(sub, obj, act)) === true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$act = "read"; // the operation that the user performs on the resource.

if ($e->enforce($sub, $obj, $act) === true) {
// permit alice to read data1
} else {
// deny the request, show an error
}
sub = "alice"  # the user that wants to access a resource.
obj = "data1" # the resource that is going to be accessed.
act = "read" # the operation that the user performs on the resource.

if e.enforce(sub, obj, act):
# permit alice to read data1
pass
else:
# deny the request, show an error
pass
var sub = "alice";  # the user that wants to access a resource.
var obj = "data1"; # the resource that is going to be accessed.
var act = "read"; # the operation that the user performs on the resource.

if (await e.EnforceAsync(sub, obj, act))
{
// permit alice to read data1
}
else
{
// deny the request, show an error
}
if casbin.enforce(['alice,data1,read']) then
// Alice is super happy as she can read data1
else
// Alice is sad
  let sub = "alice"; // the user that wants to access a resource.
let obj = "data1"; // the resource that is going to be accessed.
let act = "read"; // the operation that the user performs on the resource.

if e.enforce((sub, obj, act)).await? {
// permit alice to read data1
} else {
// error occurs
}
if e:enforce("alice", "data1", "read") then
-- permit alice to read data1
else
-- deny the request, show an error
end

Casbinには、ランタイム実行時の権限管理用の API も用意されています。例えば、ユーザーに割り当てられた全てのロールを以下のように取得できます。

Go
Java
Node.js
PHP
Python
.NET
Delphi
Rust
Lua
roles, err := e.GetRolesForUser("alice")
Roles roles = e.getRolesForUser("alice");
const roles = await e.getRolesForUser('alice');
$roles = $e->getRolesForUser("alice");
roles = e.get_roles_for_user("alice")
var roles = e.GetRolesForUser("alice");
roles = e.rolesForEntity("alice")
let roles = e.get_roles_for_user("alice");
local roles = e:GetRolesForUser("alice")

詳細については、 Management API および RBAC API を参照してください。

その他の詳細はテストケースも参照してみてください。

← 概要仕組み →
  • インストール
  • Casbin Enforcerを作成する
    • 権限のチェックする
Casbin
Docs
Getting StartedManagement APIRBAC APIMiddlewares
Community
Who's using Casbin?Stack Overflow
Casbin          jCasbin
Node-Casbin   PHP-CasbinPyCasbin          Casbin.NETCasbin-CPP        Casbin-RS
Follow @casbinHQ
Copyright © 2022 Casbin Organization