Casbin

Casbin

  • Documents
  • API
  • Editeur
  • Plugins IDE
  • Authentification unique (SSO)
  • Forums
  • Aide
  • Blogue
  • Pricing
  • Contact Sales
  • Languages iconFrançais
    • English
    • 中文
    • 한국어
    • Русский
    • Deutsch
    • 日本語
    • Aider à traduire
  • GitHub

›Les Bases

Les Bases

  • Aperçu
  • Commencer
  • Comment ça marche
  • Tutoriels

Modélisation

  • Modèles pris en charge
  • Syntaxe pour les modèles
  • Effet
  • Fonction
  • RBAC
  • RBAC avec motif
  • RBAC avec domaines
  • Casbin RBAC v.s. RBAC96
  • ABAC
  • Modèle de priorité
  • Super Admin

Stockage

  • Stockage du modèle
  • Stockage de la politique
  • Chargement du sous-ensemble de la politique

Extensions

  • Enforcers
  • Adaptateurs
  • Observateurs
  • Répartiteurs
  • Responsables des rôles
  • Moyens
  • Moyens GraphQL
  • Moyens natifs du Cloud

API

  • Aperçu de l'API
  • API de gestion
  • RBAC API
  • RBAC avec API Domains
  • API RoleManager
  • Autorisations des données

Utilisation avancée

  • Multi-threads
  • Benchmarks
  • Optimisation des performances
  • Autorisation de Kubernetes
  • Autorisation de maillage de service par l'envoyé

Gestion

  • Portail Admin
  • Service Casbin
  • Gestion des logs et des erreurs
  • Utilisation du frontend

Editeur

  • Éditeur en ligne
  • Plugins IDE

En savoir plus

  • Nos Adopteurs
  • Contribuer
  • Politique de confidentialité
  • Conditions d'utilisation
Translate

Commencer

Installation

Go
Java
https://mvnrepository.com/artifact/org.casbin/jcasbin
Node.js
PHP
Python
.NET
Rust
Delphi
Lua
allez obtenir 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 de votre projet. Cela va télécharger le paquet:

compositeur ont besoin de 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 installer casbin  

Si erreur de rapport : votre utilisateur n'a pas les permissions d'écriture dans /usr/local/lib/luarocks/rocks -- vous pouvez utiliser votre arborescence locale avec --local. vous pouvez ajouter --local derrière votre commande pour corriger :

luarocks installe casbin --local

Un nouveau responsable de Casbin

Casbin utilise des fichiers de configuration pour définir le modèle de contrôle d'accès.

Il a deux fichiers de configuration, model.conf et policy.csv. Parmi eux, model.conf stocke notre modèle d'accès, et policy.csv stocke notre configuration spécifique de permission d'utilisateur. L'utilisation de Casbin est très raffinée. Fondamentalement, nous avons juste besoin d'une structure principale : enforcecer. Lors de la construction de cette structure, model.conf et policy.csv seront chargés.

En un autre mot, pour un nouvel agent de sécurité Casbin, vous devez fournir un modèle et un adaptateur.

Casbin a un FileAdapter, voir Adapter de plus d'Adaptateur.

  • Utiliser le fichier modèle et la valeur par défaut 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");
importer { newEnforcer } depuis 'casbin';

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

utilisez Casbin\Enforcer;

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

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

var e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
var
casbin: ICasbin;
commencer
casbin := TCasbin.Create('path/to/model.conf', 'path/to/policy.csv');
...
fin
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
  • Utiliser le texte du modèle avec un autre adaptateur:
Go
Python
import (
"log"

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

// Initialise un adaptateur Xorm avec une base de données MySQL.
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 := model. ewModelFromString(`
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

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

[matchers]
m = r.sub == p.sub && r.obj == p. bj && r.act == p.act
`
)
if err != nil {
log. atalf("erreur: modèle : %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)

Vérifier les autorisations

Ajoutez un crochet d'application à votre code juste avant que l'accès ne se produise :

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 fournit également une API pour la gestion des permissions à l'exécution. Par exemple, vous pouvez obtenir tous les rôles assignés à un utilisateur comme suit:

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")

Voir Management API et RBAC API pour plus d'utilisation.

Veuillez vous référer aux cas de test pour plus d'usage.

← AperçuComment ça marche →
  • Installation
  • Un nouveau responsable de Casbin
    • Vérifier les autorisations
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