Casbin

Casbin

  • Docs
  • API
  • Editor
  • Casdoor
  • Forum
  • OA
  • Trend
  • Help
  • Blog
  • Languages iconFrançais
    • English
    • 中文
    • 한국어
    • Русский
    • 日本語
    • Help Translate
  • GitHub

›Extensions

The Basics

  • Overview
  • Get Started
  • How it Works
  • Tutorials

Model

  • Supported Models
  • Syntax for Models
  • Function
  • RBAC
  • RBAC with Domains
  • Casbin RBAC v.s. RBAC96
  • ABAC
  • Priority Model

Storage

  • Model Storage
  • Policy Storage
  • Policy Subset Loading

Extensions

  • Adapters
  • Watchers
  • Dispatchers
  • Role Managers
  • Middlewares

API

  • API tutorial
  • Management API
  • RBAC API
  • RoleManager API
  • Data-permissions

Advanced Usage

  • Multi-threading
  • Benchmarks
  • Performance Optimization

Management

  • Admin Portal
  • Casbin Service
  • Log & Error Handling
  • Frontend Usage

Editor

  • Online Editor
  • IDE Plugins

More

  • Our Adopters
  • Privacy Policy
  • Terms of Service
Translate

Adapters

In Casbin, the policy storage is implemented as an adapter (aka middleware for Casbin). A Casbin user can use an adapter to load policy rules from a storage (aka LoadPolicy()), or save policy rules to it (aka SavePolicy()). To keep light-weight, we don't put adapter code in the main library.

Supported adapters

A complete list of Casbin adapters is provided as below. Any 3rd-party contribution on a new adapter is welcomed, please inform us and we will put it in this list:)

Go
Java
Node.js
PHP
Python
.NET
Rust
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
Filtered File Adapter (built-in)File@faceless-saint❌For .CSV (Comma-Separated Values) files with policy subset loading support
SQL AdapterSQL@Blank-Xu✅MySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by database/sql
Xorm AdapterORMCasbin✅MySQL, PostgreSQL, TiDB, SQLite, SQL Server, Oracle are supported by Xorm
Gorm AdapterORMCasbin✅MySQL, PostgreSQL, Sqlite3, SQL Server are supported by Gorm
Beego ORM AdapterORMCasbin✅MySQL, PostgreSQL, Sqlite3 are supported by Beego ORM
SQLX AdapterORM@memwey✅MySQL, PostgreSQL, SQLite, Oracle are supported by SQLX
Sqlx AdapterSQL@Blank-Xu✅MySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by sqlx
GF ORM AdapterORM@vance-liu✅MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
GoFrame ORM AdapterORM@kotlin2018✅MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
Filtered PostgreSQL AdapterSQLCasbin✅For PostgreSQL
PostgreSQL AdapterSQL@cychiuae✅For PostgreSQL
PostgreSQL Adapter (Archived)SQLGoing❌For PostgreSQL
RQLite AdapterSQLEDOMO Systems✅For RQLite
MongoDB AdapterNoSQLCasbin✅For MongoDB based on MongoDB driver for Go
RethinkDB AdapterNoSQL@adityapandey9✅For RethinkDB
Cassandra AdapterNoSQLCasbin❌For Apache Cassandra DB
DynamoDB AdapterNoSQLHOOQ❌For Amazon DynamoDB
DynacasbinNoSQLNewbMiao✅For Amazon DynamoDB
ArangoDB AdapterNoSQL@adamwasila✅For ArangoDB
Amazon S3 AdapterCloudSoluto❌For Minio and Amazon S3
Azure Cosmos DB AdapterCloud@spacycoder✅For Microsoft Azure Cosmos DB
GCP Firestore AdapterCloud@reedom❌For Google Cloud Platform Firestore
GCP Cloud Storage AdapterCloudqurami❌For Google Cloud Platform Cloud Storage
Consul AdapterKV store@ankitm123❌For HashiCorp Consul
Redis AdapterKV storeCasbin❌For Redis
Etcd AdapterKV store@sebastianliu❌For etcd
BoltDB AdapterKV store@speza✅For Bolt
Bolt AdapterKV store@wirepair❌For Bolt
BadgerDB AdapterKV store@inits✅For BadgerDB
Protobuf AdapterStreamCasbin❌For Google Protocol Buffers
JSON AdapterStringCasbin❌For JSON
String AdapterString@qiangmzsx❌For String
HTTP File AdapterHTTP@h4ckedneko❌For http.FileSystem
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
JDBC AdapterJDBCCasbin✅MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server are supported by JDBC
Hibernate AdapterORMCasbin✅Oracle, DB2, SQL Server, Sybase, MySQL, PostgreSQL are supported by Hibernate
MyBatis AdapterORMCasbin✅MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server (the same as JDBC) are supported by MyBatis 3
Hutool AdapterORM@mapleafgo✅MySQL, Oracle, PostgreSQL, SQLite are supported by Hutool
MongoDB AdapterNoSQLCasbin✅MongoDB is supported by mongodb-driver-sync
DynamoDB AdapterNoSQLCasbin❌For Amazon DynamoDB
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
Filtered File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files with policy subset loading support
String Adapter (built-in)String@calebfaruki❌For String
Basic AdapterNative ORMCasbin✅pg, mysql, mysql2, sqlite3, oracledb, mssql are supported by the adapter itself
Sequelize AdapterORMCasbin✅MySQL, PostgreSQL, SQLite, Microsoft SQL Server are supported by Sequelize
TypeORM AdapterORMCasbin✅MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL, MongoDB are supported by TypeORM
Prisma AdapterORMCasbin✅MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, AWS Aurora, Azure SQL are supported by Prisma
Knex AdapterORM@sarneeh and knex✅MSSQL, MySQL, PostgreSQL, SQLite3, Oracle are supported by Knex.js
Objection.js AdapterORM@willsoto✅MSSQL, MySQL, PostgreSQL, SQLite3, Oracle are supported by Objection.js
Node PostgreSQL Native AdapterSQL@touchifyapp✅PostgreSQL adapter with advanced policy subset loading support and improved performances built with node-postgres.
Mongoose AdapterNoSQLelastic.io and Casbin✅MongoDB is supported by Mongoose
Node MongoDB Native AdapterNoSQL@juicycleff✅For Node MongoDB Native
DynamoDB AdapterNoSQL@fospitia✅For Amazon DynamoDB
Couchbase AdapterNoSQL@MarkMYoung✅For Couchbase
Redis AdapterKV storeCasbin❌For Redis
Redis AdapterKV store@NandaKishorJeripothula❌For Redis
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
Database AdapterORMCasbin✅MySQL, PostgreSQL, SQLite, Microsoft SQL Server are supported by techone/database
Zend Db AdapterORMCasbin✅MySQL, PostgreSQL, SQLite, Oracle, IBM DB2, Microsoft SQL Server, Other PDO Driver are supported by zend-db
Doctrine DBAL Adapter (Recommend)ORMCasbin✅Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
Medoo AdapterORMCasbin✅Medoo is a lightweight PHP Database Framework to Accelerate Development, supports all SQL databases, including MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle and more.
Laminas-db AdapterORMCasbin✅MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO, etc. are supported by laminas-db
Zend-db AdapterORMCasbin✅MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO, etc. are supported by zend-db
Redis AdapterKV store@nsnake❌For Redis
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
SQLAlchemy AdapterORMCasbin✅PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by SQLAlchemy
Async Databases AdapterORMCasbin✅PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by Databases
Peewee AdapterORM@shblhy✅PostgreSQL, MySQL, SQLite are supported by Peewee
MongoEngine AdapterORM@zhangbailong945❌MongoDB is supported by MongoEngine
Couchbase AdapterNoSQLScienceLogic✅ (without remove_filtered_policy())For Couchbase
DynamoDB AdapterNoSQL@abqadeer✅For DynamoDB
Pymongo AdapterNoSQLCasbin❌MongoDB is supported by Pymongo
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
EF AdapterORMCasbin❌MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework 6
EFCore AdapterORMCasbin✅MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework Core
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbin❌For .CSV (Comma-Separated Values) files
Diesel AdapterORMCasbin✅SQLite, PostgreSQL, MySQL are supported by Diesel
Sqlx AdapterORMCasbin✅PostgreSQL, MySQL are supported by Sqlx with fully asynchronous operation
YAML AdapterStringCasbin✅For YAML
note
  1. If casbin.NewEnforcer() is called with an explicit or implicit adapter, the policy will be loaded automatically.
  2. You can call e.LoadPolicy() to reload the policy rules from the storage.
  3. If the adapter does not support the Auto-Save feature, The policy rules cannot be automatically saved back to the storage when you add or remove policies. You have to call SavePolicy() manually to save all policy rules.

Examples

Here we provide several examples:

File adapter (built-in)

Below shows how to initialize an enforcer from the built-in file adapter:

Go
PHP
Rust
import "github.com/casbin/casbin"

e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
use Casbin\Enforcer;

$e = new Enforcer('examples/basic_model.conf', 'examples/basic_policy.csv');
use casbin::prelude::*;

let mut e = Enforcer::new("examples/basic_model.conf", "examples/basic_policy.csv").await?;

This is the same with:

Go
PHP
Rust
import (
"github.com/casbin/casbin"
"github.com/casbin/casbin/file-adapter"
)

a := fileadapter.NewAdapter("examples/basic_policy.csv")
e := casbin.NewEnforcer("examples/basic_model.conf", a)
use Casbin\Enforcer;
use Casbin\Persist\Adapters\FileAdapter;

$a = new FileAdapter('examples/basic_policy.csv');
$e = new Enforcer('examples/basic_model.conf', $a);
use casbin::prelude::*;

let a = FileAdapter::new("examples/basic_policy.csv");
let e = Enforcer::new("examples/basic_model.conf", a).await?;

MySQL adapter

Below shows how to initialize an enforcer from MySQL database. it connects to a MySQL DB on 127.0.0.1:3306 with root and blank password.

Go
Rust
PHP
import (
"github.com/casbin/casbin"
"github.com/casbin/mysql-adapter"
)

a := mysqladapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/")
e := casbin.NewEnforcer("examples/basic_model.conf", a)
// https://github.com/casbin-rs/diesel-adapter
// make sure you activate feature `mysql`

use casbin::prelude::*;
use diesel_adapter::{ConnOptions, DieselAdapter};

let mut conn_opts = ConnOptions::default();
conn_opts
.set_hostname("127.0.0.1")
.set_port(3306)
.set_host("127.0.0.1:3306") // overwrite hostname, port config
.set_database("casbin")
.set_auth("casbin_rs", "casbin_rs");

let a = DieselAdapter::new(conn_opts)?;
let mut e = Enforcer::new("examples/basic_model.conf", a).await?;
// https://github.com/php-casbin/dbal-adapter

use Casbin\Enforcer;
use CasbinAdapter\DBAL\Adapter as DatabaseAdapter;

$config = [
// Either 'driver' with one of the following values:
// pdo_mysql,pdo_sqlite,pdo_pgsql,pdo_oci (unstable),pdo_sqlsrv,pdo_sqlsrv,
// mysqli,sqlanywhere,sqlsrv,ibm_db2 (unstable),drizzle_pdo_mysql
'driver' => 'pdo_mysql',
'host' => '127.0.0.1',
'dbname' => 'test',
'user' => 'root',
'password' => '',
'port' => '3306',
];

$a = DatabaseAdapter::newAdapter($config);
$e = new Enforcer('examples/basic_model.conf', $a);

Use your own storage adapter

You can use your own adapter like below:

import (
    "github.com/casbin/casbin"
    "github.com/your-username/your-repo"
)

a := yourpackage.NewAdapter(params)
e := casbin.NewEnforcer("examples/basic_model.conf", a)

Load/Save at run-time

You may also want to reload the model, reload the policy or save the policy after initialization:

// Reload the model from the model CONF file.
e.LoadModel()

// Reload the policy from file/database.
e.LoadPolicy()

// Save the current policy (usually after changed with Casbin API) back to file/database.
e.SavePolicy()

AutoSave

There is a feature called Auto-Save for adapters. When an adapter supports Auto-Save, it means it can support adding a single policy rule to the storage, or removing a single policy rule from the storage. This is unlike SavePolicy(), because the latter will delete all policy rules in the storage and save all policy rules from Casbin enforcer to the storage. So it may suffer performance issue when the number of policy rules is large.

When the adapter supports Auto-Save, you can switch this option via Enforcer.EnableAutoSave() function. The option is enabled by default (if the adapter supports it).

note
  1. The Auto-Save feature is optional. An adapter can choose to implement it or not.
  2. Auto-Save only works for a Casbin enforcer when the adapter the enforcer uses supports it.
  3. See the AutoSave column in the above adapter list to see if Auto-Save is supported by an adapter.

Here's an example about how to use Auto-Save:

import (
    "github.com/casbin/casbin"
    "github.com/casbin/xorm-adapter"
    _ "github.com/go-sql-driver/mysql"
)

// By default, the AutoSave option is enabled for an enforcer.
a := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
e := casbin.NewEnforcer("examples/basic_model.conf", a)

// Disable the AutoSave option.
e.EnableAutoSave(false)

// Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,
// it doesn't affect the policy in the storage.
e.AddPolicy(...)
e.RemovePolicy(...)

// Enable the AutoSave option.
e.EnableAutoSave(true)

// Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,
// but also affects the policy in the storage.
e.AddPolicy(...)
e.RemovePolicy(...)

For more examples, please see: https://github.com/casbin/xorm-adapter/blob/master/adapter_test.go

How to write an adapter

All adapters should implement the Adapter interface by providing at least two mandatory methods:LoadPolicy(model model.Model) error and SavePolicy(model model.Model) error.

The other three functions are optional. They should be implemented if the adapter supports the Auto-Save feature.

MethodTypeDescription
LoadPolicy()mandatoryLoad all policy rules from the storage
SavePolicy()mandatorySave all policy rules to the storage
AddPolicy()optionalAdd a policy rule to the storage
RemovePolicy()optionalRemove a policy rule from the storage
RemoveFilteredPolicy()optionalRemove policy rules that match the filter from the storage
note

If an adapter doesn't support Auto-Save, it should provide an empty implementation for the three optional functions. Here's an example for Golang:

// AddPolicy adds a policy rule to the storage.
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
    return errors.New("not implemented")
}

// RemovePolicy removes a policy rule from the storage.
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
    return errors.New("not implemented")
}

// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
    return errors.New("not implemented")
}

Casbin enforcer will ignore the not implemented error when calling these three optional functions.

Who is responsible to create the DB?

As a convention, the adapter should be able to automatically create a database named casbin if it doesn't exist and use it for policy storage. Please use the Xorm adapter as a reference implementation: https://github.com/casbin/xorm-adapter

← Policy Subset LoadingWatchers →
  • Supported adapters
  • Examples
    • File adapter (built-in)
    • MySQL adapter
  • Use your own storage adapter
  • Load/Save at run-time
  • AutoSave
    • How to write an adapter
    • Who is responsible to create the DB?
Casbin
Docs
Getting StartedManagement APIRBAC APIMiddlewares
Community
Who's using Casbin?ForumStack OverflowProject Chat
Casbin          jCasbin
Node-Casbin   PHP-CasbinPyCasbin          Casbin.NETCasbin-CPP        Casbin-RS
Follow @CasbinNews
Copyright © 2021 Casbin contributors.