Get Started
การติดตั้ง
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- C++
- Rust
- Delphi
- Lua
go get 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>
GraalVM Native Image Support
If you're building a native application with GraalVM (e.g., using Quarkus or Spring Native), jCasbin requires special configuration due to its use of the Aviator expression engine.
By default, Aviator uses dynamic class generation via ASM, which is not supported in GraalVM native images. To resolve this, you must configure Aviator to use interpreter mode instead of compilation mode.
For Quarkus applications
Add the following to your application.properties
or pom.xml
:
<properties>
<quarkus.native.additional-build-args>
-J-Daviator.eval.mode=INTERPRETER
</quarkus.native.additional-build-args>
</properties>
For other GraalVM native builds
Set the system property when building the native image:
-Daviator.eval.mode=INTERPRETER
Or configure it programmatically before initializing jCasbin:
System.setProperty("aviator.eval.mode", "INTERPRETER");
This configuration switches Aviator from its default compilation mode to interpreter mode. While this may have a slight performance impact, it enables full compatibility with GraalVM native images by avoiding runtime class generation.
# 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, make sure you activate its `macros` feature
cargo add tokio
Casbin4D มาในรูปแบบแพ็คเกจ (ปัจจุบันสำหรับ Delphi 10.3 Rio) และคุณสามารถติดตั้งได้ใน IDE. อย่างไรก็ตาม ไม่มีส่วนประกอบทางภาพ ซึ่งหมายความว่าคุณสามารถใช้ยูนิตได้อย่างอิสระจากแพ็คเกจ เพียงนำเข้ายูนิตในโปรเจกต์ของคุณ (โดยสมมติว่าคุณไม่รังเกียจจำนวนของพวกเขา)
luarocks install casbin
หากคุณได้รับข้อความแสดงข้อผิดพลาด: "Your user does not have write permissions in /usr/local/lib/luarocks/rocks", คุณอาจต้องการทำคำสั่งด้วยสิทธิ์ผู้ใช้ที่มีสิทธิ์มากขึ้นหรือใช้ต้นไม้ท้องถิ่นของคุณด้วย --local
. เพื่อแก้ไขข้อผิดพลาด คุณสามารถเพิ่ม --local
ไว้ข้างหลังคำสั่งของคุณเช่นนี้:
luarocks install casbin --local
สร้าง Casbin enforcer ใหม่
Casbin ใช้ไฟล์การกำหนดค่าเพื่อกำหนดโมเดลการควบคุมการเข้าถึง
มีไฟล์การกำหนดค่าสองไฟล์: model.conf
และ policy.csv
. model.conf
เก็บโมเดลการเข้าถึง ขณะที่ policy.csv
เก็บการกำหนดค่าสิทธิ์ผู้ใช้เฉพาะ การใช้งาน Casbin นั้นง่ายมาก เราเพียงต้องการสร้างโครงสร้างหลักเพียงอย่างเดียว: enforcer. เมื่อสร้างโครงสร้างนี้ model.conf
และ policy.csv
จะถูกโหลด
กล่าวอีกนัยหนึ่ง ในการสร้าง Casbin enforcer คุณต้องการให้มี Model และ Adapter.
Casbin มี FileAdapter ที่คุณสามารถใช้ได้ ดู Adapter เพื่อข้อมูลเพิ่มเติม
- ตัวอย่างการใช้ไฟล์ Model และ 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
- ใช้ข้อความ Model กับ 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)/")
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)
ตรวจสอบสิทธิ์
เพิ่มตะขอการบังคับใช้ลงในโค้ดของคุณก่อนที่การเข้าถึงจะเกิดขึ้น:
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- C++
- 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
}
If you're running jCasbin in a GraalVM native image environment, make sure you've configured Aviator to use interpreter mode as described in the installation section above. Without this configuration, you'll encounter an UnsupportedFeatureError
due to runtime class generation attempts.
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
}
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 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")
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")
ดู Management API และ RBAC API เพื่อการใช้งานเพิ่มเติม
โปรดดูที่กรณีทดสอบเพื่อการใช้งานเพิ่มเติม