Los geht's
Installation
go get github.com/casbin/casbin/v2
<dependency>
<groupId>org.casbin</groupId>
<artifactId>jcasbin</artifactId>
<version>1.x.y</version>
</dependency>
# NPM
npm casbin installieren --save
# Yarn
yarn add casbin
composer.json
Ihres Projekts. Dies wird das Paket herunterladen:
Komponist benötigt Kasbin/Kasbin
pip install casbin
dotnet add Paket 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 casbin installieren
Wenn Berichtfehler: Ihr Benutzer hat keine Schreibrechte in /usr/local/lib/luarocks/rocks -- Sie können als privilegierter Benutzer laufen lassen oder Ihren lokalen Baum mit --local verwenden. Sie können --local hinter Ihrem Befehl einfügen, um dies zu beheben:
luarocks install casbin --local
Neuer Casbin-Vollstrecker
Casbin verwendet Konfigurationsdateien, um das Zugriffskontrollmodell festzulegen.
Es hat zwei Konfigurationsdateien, model.conf
und policy.csv
. Unter ihnen speichert model.conf
unser Zugriffsmodell und policy.csv
speichert unsere spezifische Benutzerberechtigungskonfiguration. Die Nutzung von Casbin ist sehr verfeinert. Im Grunde brauchen wir nur eine Hauptstruktur: Durchsetzer. Beim Bau dieser Struktur werden model.conf
und policy.csv
geladen.
In einem anderen Wort, um einen Casbin-Vollstrecker neu zu machen, müssen Sie ein -Modell und einen Adapter angeben.
Casbin hat einen FileAdapter, siehe Adapter von mehr Adapter.
- Verwende die Modelldatei und den Standard FileAdapter:
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/zu/model.conf", "path/zu/policy.csv");
{ newEnforcer } von 'casbin' importieren;
const e = warten newEnforcer('path/to/model.conf', 'path/to/policy.csv');
require_once './vendor/autoload.php';
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")
mit NetCasbin;
var e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
var
casbin: ICasbin;
beginnen
casbin := TCasbin.Create('path/to/model.conf', 'path/to/policy.csv');
...
enden
benutze Casbin::prelude::*;
// Wenn Sie async_td als async executor verwenden
#[cfg(feature = "runtime-async-std")]
#[async_std::main]
async fn main() -> Result<()> {
let mut e = Enforcer::new("path/to/model). onf", "path/to/policy.csv"). warten?;
Ok())
}
// Wenn Sie tokio als async executor verwenden
#[cfg(feature = "runtime-tokio")]
#[tokio::main]
async fn main() -> Result<()> {
let mut e = Enforcer::new("path/to/model). onf", "path/to/policy.csv").await?;
Ok())
}
local Enforcer = require("casbin")
local e = Enforcer:new("path/to/model.conf", "path/to/policy.csv") -- Der Casbin Enforcer
- Den Modelltext mit einem anderen Adapter verwenden:
import (
"log"
"github.com/casbin/v2"
"github.com/casbin/casbin/v2/model"
xormadapter "github.com/casbin/xorm-adapter/v2"
_ "github.com/go-sql-driver/mysql"
)
// Xorm-Adapter mit MySQL-Datenbank initialisieren.
a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0. :3306)/casbin")
if err != nil {
log.Fatalf("error: adapter: %s", err)
}
m, err := Modell. ewModelFromString(`
[request_definition]
r = sub, obj, handeln
[policy_definition]
p = sub, obj, handeln
[policy_effect]
e = irgendwann, wo (p. ft == allow))
[matchers]
m = r.sub == p.sub && r.obj == p. bj && r.act == p.act
`)
if err != nil {
log. atalf("error: model: %s", err)
}
e, err := casbin. ewEnforcer(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)
Berechtigungen überprüfen
Fügen Sie einen Strafverfolgungshaken direkt vor dem Zugriff in Ihren Code ein:
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 stellt auch die API für die Verwaltung von Berechtigungen zur Laufzeit zur Verfügung. Zum Beispiel können Sie alle Rollen einem Benutzer wie unten zugewiesen bekommen:
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")
Siehe Management API und RBAC API für mehr Nutzung.
Bitte beachten Sie die Testfälle für mehr Verwendung.