시작하기
설치
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- C++
- Rust
- Delphi
- Lua
github.com/casbin/casbin/v2 으로
Maven에서
<!-- https://mvnrepository.com/artifact/org.casbin/jcasbin -->
<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
파일에 아래 패키지를 포함하세요. 아래와 같이 다운로드할 수 있습니다.
composer require casbin/casbin
pip install casbin
dotnet add package Casbin.NET
# download source
git clone https://github.com/casbin/casbin-cpp.git
# generate project files
cd casbin-cpp && mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release
# build and install casbin
cmake --build . --config Release --target casbin install -j 10
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
Casbin4D는 패키지에 포함되어 있습니다. (Delphi 10.3 Rio 이상) IDE에서 설치할 수 있습니다. 단 컴포넌트에는 나타나지 않으니 패키지에서 각 요소를 따로 불러와 사용해야 합니다. 그냥 각 요소를 import 하면 됩니다. (개수에 신경쓰지 않으시길)
luarocks install casbin
If report Error: Your user does not have write permissions in /usr/local/lib/luarocks/rocks -- you may want to run as a privileged user or use your local tree with --local. you can add --local behind your command like this to fix:
luarocks install casbin --local
New a Casbin enforcer
Casbin uses configuration files to set the access control model.
It has two configuration files, model.conf
and policy.csv
. Among them, model.conf
stores our access model, and policy.csv
stores our specific user permission configuration. The use of Casbin is very refined. Basically, we just need one main structure: enforcer. When constructing this structure, model.conf
and policy.csv
will be loaded.
In another word, to new a Casbin enforcer, you must provide a Model and an Adapter.
Casbin has a FileAdapter, see Adapter for more information.
- Use the Model file and default FileAdapter:
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- C++
- 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");
#include <iostream>
#include <casbin/casbin.h>
int main() {
// Create an Enforcer
casbin::Enforcer e("path/to/model.conf", "path/to/policy.csv");
// your code ..
}
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
- Use the Model text with other Adapter:
- 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)
Check permissions
접근을 통제할 코드 부분에 검사 조건문을 추가하세요.
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- C++
- Delphi
- Rust
- Lua
sub := "alice" // 보안 주체
obj := "data1" // 접근 대상 리소스
act := "read" // 보안 주체가 리소스에 대해 수행하려는 동작
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"; // 보안 주체
String obj = "data1"; // 접근 대상 리소스
String act = "read"; // 보안 주체가 리소스에 대해 수행하려는 동작
if (e.enforce(sub, obj, act) == true) {
// alice에게 data1에 대한 read를 허용
} else {
// 요청 거부 및 오류 출력
}
const sub = 'alice'; // 보안 주체
const obj = 'data1'; // 접근 대상 리소스
const act = 'read'; // 보안 주체가 리소스에 대해 수행하려는 동작
if ((await e.enforce(sub, obj, act)) === true) {
// alice에게 data1에 대한 read를 허용
} else {
// 요청 거부 및 오류 출력
}
$sub = "alice"; // 보안 주체
$obj = "data1"; // 접근 대상 리소스
$act = "read"; // 보안 주체가 리소스에 대해 수행하려는 동작
if ($e->enforce($sub, $obj, $act) === true) {
// alice에게 data1에 대한 read를 허용
} else {
// 요청 거부 및 오류 출력
}
sub = "alice" # 보안 주체
obj = "data1" # 접근 대상 리소스
act = "read" # 보안 주체가 리소스에 대해 수행하려는 동작
if e.enforce(sub, obj, act):
# alice에게 data1에 대한 read를 허용
pass
else:
# 요청 거부 및 오류 출력
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
}
casbin::Enforcer e("../assets/model.conf", "../assets/policy.csv");
if (e.Enforce({"alice", "/alice_data/hello", "GET"})) {
std::cout << "Enforce OK" << std::endl;
} else {
std::cout << "Enforce NOT Good" << std::endl;
}
if (e.Enforce({"alice", "/alice_data/hello", "POST"})) {
std::cout << "Enforce OK" << std::endl;
} else {
std::cout << "Enforce NOT Good" << std::endl;
}
if casbin.enforce(['alice,data1,read']) then
// Alice는 data1에 대한 read 가능
else
// Alice 요청 거부
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 also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- Delphi
- Rust
- Lua
roles, err := e.GetRolesForUser("alice")
List<String> 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")
See Management API and RBAC API for more usage.
더 많은 사용법을 알아보려면 테스트 케이스도 참조하세요.