适配器
在Casbin中,策略存储作为adapter(Casbin的中间件) 实现。 Casbin用户可以使用adapter从存储中加载策略规则 (aka LoadPolicy()
) 或者将策略规则保存到其中 (aka SavePolicy()
)。 为了保持代码轻量级,我们没有把adapter代码放在主库中。
目前支持的适配器列表
Casbin的适配器完整列表如下。 我们欢迎任何第三方对adapter进行新的贡献,如果有请通知我们,我们将把它放在这个列表中:)
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- Rust
- Ruby
- Swift
- Lua
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
JDBC Adapter | JDBC | Casbin | ✅ | MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL 服务器由 JDBC 支持 |
Hibernate Adapter | ORM | Casbin | ✅ | Oracle, DB2, SQL Server, Sybase, MySQL, PostgreSQL 由 Hibernate支持 |
MyBatis Adapter | ORM | Casbin | ✅ | MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server (与 JDBC 相同) 由 MyBatis 3 支持 |
Hutool Adapter | ORM | @mapleafgo | ✅ | MySQL, Oracle, PostgreSQL, SQLite 由 Hutool 支持 |
MongoDB Adapter | NoSQL | Casbin | ✅ | MongoDB 由 Mongodb-driver-sync 支持 |
DynamoDB Adapter | NoSQL | Casbin | ❌ | 用于 Amazon DynamoDB |
Redis Adapter | KV store | Casbin | ✅ | 用于 Redis |
适配器 | 实现要素 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Filtered File Adapter (内置) | File | Casbin | ❌ | 对于 CSV (逗号分隔的值) 个带策略子集加载支持的文件 |
String Adapter (内置) | String | @calebfaruki | ❌ | 用于字符串 |
Basic Adapter | Native ORM | Casbin | ✅ | pg, mysql, mysql2, sqlite3, oracedb, mssql 是适配器本身支持的 |
Sequelize Adapter | ORM | Casbin | ✅ | MySQL、 PostgreSQL、 SQLite、 Microsoft SQL Server 由 Sequelize 支持 |
TypeORM Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL, MongoDB 由 TypeORM 支持 |
Prisma Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, AWS Aurora, Azure SQL 由 Prisma支持 |
Knex Adapter | ORM | knex | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Knex.js支持 |
Objection.js Adapter | ORM | @willsoto | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Objection.js 支持 |
MikroORM Adapter | ORM | @baisheng | ✅ | MongoDB, MySQL, MariaDB, PostgreSQL, SQLite are supported by MikroORM |
Node PostgreSQL Native Adapter | SQL | @touchifyapp | ✅ | PostgreSQL 适配器,拥有高级策略子集加载支持以及由 [node-postgres](https://node-postgres. com/) 构建的更好的性能。 |
MongoDB Adapter | NoSQL | elastic.io 和 Casbin | ✅ | MongoDB 由 Mongoose 支持 |
Mongoose 适配器 (无交易) | NoSQL | minhducck | ✅ | MongoDB is supported by Mongoose |
Node MongoDB Native Adapter | NoSQL | @juicycleff | ✅ | 用于 Node MongoDB Native |
DynamoDB Adapter | NoSQL | @fospitia | ✅ | 用于 Amazon DynamoDB |
Couchbase Adapter | NoSQL | @MarkMYoung | ✅ | 用于 Couchbase |
Redis Adapter | KV store | Casbin | ❌ | 用于 Redis |
Redis Adapter | KV store | @NandaKishorJeripothula | ❌ | For Redis |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
数据库适配器 | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server 由 techone/database 支持 |
Zend Db 适配器 | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Oracle, IBM DB2, Microsoft SQL Server, 其他 PDO Driver 由 zend-db 支持 |
Doctrine DBAL 适配器(建议) | ORM | Casbin | ✅ | 强大的 PHP 数据库抽象层(DBAL),具有数据库架构内省和管理的许多功能。 |
Medoo 适配器 | ORM | Casbin | ✅ | Medoo 是一个用来加速开发的轻量PHP 数据库框架。 支持所有 SQL 数据库,包括 MySQL , MSSQL , SQLite , MariaDB , PostgreSQL , Sybase , Oracle 以及更多。 |
Laminas-db 适配器 | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PDO, etc. are supported by laminas-db |
Zend-db 适配器 | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PDO, etc. are supported by zend-db |
ThinkORM Adapter (ThinkPHP) | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Oracle, Microsoft SQL Server, MongoDB are supported by ThinkORM |
Redis Adapter | KV store | @nsnake | ❌ | 用于 Redis |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Django ORM Adapter | ORM | Casbin | ✅ | PostgreSQL、MariaDB、MySQL、Oracle、SQLite、IBM DB2、Microsoft SQL Server、Firebird、ODBC 都由 Django ORM 支持 |
SQLObject Adapter | ORM | Casbin | ✅ | PostgreSQL、MySQLite、Microsoft SQL Server、Firebird、Sybase、MAX DB、pyfirebirdsql 都由 SQLObject 支持。 |
SQLAlchemy 适配器 | ORM | Casbin | ✅ | PostgreSQL、MySQLite、Oracle、Microsoft SQL Server、Firebird、Sybase 由 SQLAlchemy 支持 |
Async SQLAlchemy Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by SQLAlchemy |
异步数据库适配器 | ORM | Casbin | ✅ | PostgreSQL、MySQLite、Oracle、Microsoft SQL Server、Firebird、Sybase 由 Databases 支持。 |
Peewee 适配器 | ORM | @shblhy | ✅ | PostgreSQL、 MySQL、 SQLite 由 Peewee 支持 |
MongoEngine 适配器 | ORM | @zhangbailong945 | ❌ | MongoDB 由 MongoEngine 支持 |
Pony ORM Adapter | ORM | @drorvinkler | ✅ | MySQL, PostgreSQL, SQLite, Oracle, CockroachDB由Pony ORM支持 |
Tortoise ORM Adapter | ORM | @thearchitector | ✅ | PostgreSQL (>=9.4)、 MySQL、MariaDB 和 SQLite 由 Tortoise ORM 支持 |
Async Ormar Adapter | ORM | @shepilov-vladislav | ✅ | PostgreSQL、MySQL、SQLite 由 Ormar 支持 |
SQLModel Adapter | ORM | @shepilov-vladislav | ✅ | PostgreSQL、MySQL、SQLite 由 SQLModel |
Couchbase Adapter | NoSQL | ScienceLogic | ✅ (没有 remove_filtered_policy() ) | 用于 Couchbase |
DynamoDB Adapter | NoSQL | @abqadeer | ✅ | 用于 DynamoDB |
Pymongo 适配器 | NoSQL | Casbin | ❌ | MongoDB 由 [Pymongo 支持](https://pypi. org/project/pymongo/) |
Redis Adapter | KV store | Casbin | ✅ | For Redis |
GCP Firebase Adapter | Cloud | @devrushi41 | ✅ | 用于Google Cloud Platform Firebase |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
EF 适配器 | ORM | Casbin | ❌ | MySQL、 PostgreSQL、 SQLite、 Microsoft SQL Server、 Oracle, DB2 等都由 Entity Framework 6 支持。 |
EFCore 适配器 | ORM | Casbin | ✅ | MySQL, PostgreSQL、 SQLite,、Microsoft SQL Server、Oracle、DB2, 等都由 Entity Framework Core支持 |
Linq2DB Adapter | ORM | @Tirael | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, Access, Firebird, Sybase, etc. are supported by linq2db |
Azure Cosmos DB Adapter | Cloud | @sagarkhandelwal | ✅ | For Microsoft Azure Cosmos DB |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Diesel 适配器 | ORM | Casbin | ✅ | SQLite, PostgreSQL, MySQL 由 Diesel 支持 |
Sqlx Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL 由 Sqlx 支持,可实现完全异步操作 |
SeaORM Adapter | ORM | @lingdu1234 | ✅ | PostgreSQL, MySQL, SQLite are supported by SeaORM with fully asynchronous operation |
SeaORM Adapter | ORM | @ZihanType | ✅ | PostgreSQL, MySQL, SQLite are supported by SeaORM with fully asynchronous operation |
Rbatis Adapter | ORM | rbatis | ✅ | MySQL, PostgreSQL, SQLite, SQL Server, MariaDB, TiDB, CockroachDB, Oracle are supported by Rbatis |
DynamodDB Adapter | NoSQL | @fospitia | ✅ | 用于Amazon DynamoDB |
MongoDB Adapter | MongoDB | @wangjun861205 | ✅ | For MongoDB |
JSON Adapter | String | Casbin | ✅ | 用于JSON |
YAML 适配器 | String | Casbin | ✅ | 用于 [YAML](https://yaml. org/) |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Memory Adapter (内置) | 内存 | Casbin | ❌ | 用于内存 |
Fluent Adapter | ORM | Casbin | ✅ | PostgreSQL、SQLite、MySQL、MongoDB 由 Fluent 支持 |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Filtered File Adapter (内置) | File | Casbin | ❌ | 对于 CSV (逗号分隔的值) 个带策略子集加载支持的文件 |
LuaSQL Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite3 are supported by LuaSQL |
4DaysORM Adapter | ORM | Casbin | ✅ | MySQL, SQLite3 由 4DaysORM支持 |
OpenResty Adapter | ORM | @tom2nonames | ✅ | MySQL, PostgreSQL are supported by it |
- 如果使用显式或隐式adapter调用
casbin.NewEnforcer()
,策略将自动加载。 - 可以调用
e.LoadPolicy()
来从存储中重新加载策略规则。 - 如果adapter不支持
Auto-Save
特性,则在添加或删除策略时不能将策略规则自动保存回存储器。 你必须手动调用SavePolicy()
来保存所有的策略规则
例子
我们为您提供以下示例作为参考:
文件适配器 (内置)
下面的代码演示了如何从File adapter初始化enforcer:
- 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?;
它等同于如下代码:
- 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 适配器
下面展示了如何从MySQL数据库初始化一个enforcer。 此处样例中的MySQL数据库运行在127.0.0.1:3306上,用户为root,密码为空。
- 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
// 请确保您激活了 `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);
使用自建的adapter
您可以参考如下代码来使用自建的adapter
import (
"github.com/casbin/casbin"
"github.com/your-username/your-repo"
)
a := yourpackage.NewAdapter(params)
e := casbin.NewEnforcer("examples/basic_model.conf", a)
在不同适配器之间转移/转换
如果您想将适配器从 A
转换为 B
, 您可以这样做:
从 A 加载策略到内存
e, _ := NewEnforcer(m, A)
或者
e.SetAdapter(A)
e.LoadPolicy()将您的适配器从 A 转换为 B
e.SetAdapter(B)
将策略从内存保存到 B
e.SavePolicy()
在运行时进行加载或保存配置信息
如果您在初始化后仍想重载model和policy的配置(或是保存policy的配置信息),那么可以参照如下方法:
// 从CONF配置文件中加载model
e.LoadModel()
// 从文件或数据库中加载policy
e. LoadPolicy()
// 保存当前的policy(通常在调用Casbin API改变了配置信息后)至文件或数据库
e.SavePolicy()
自动保存
自动保存机制(Auto-Save
)是adapter的特性之一。 支持自动保存机制的adapter可以自动向存储回写内存中单个policy规则的变更(删除/更新)。 与自动回写机制不同,调用SavePolicy()
会直接删除所有存储中的policy规则并将当前Casbin enforcer
存储在内存中的policy规则悉数持久化到存储中。 因此,当内存中的policy规则过多时,直接调用SavePolicy()
会引起一些性能问题。
当适配器支持自动保存机制时,您可以通过Enforcer.EnableAutoSave()
函数来开启或关闭该机制。 默认情况下启用该选项(如果适配器支持自动保存的话)。
Auto-Save
特性是可选的。 Adapter可以选择是否实现它。Auto-Save
只在Casbin enforcer使用的adapter支持它时才有效。- 查看上述adapter列表中的
AutoSave
列,查看adapter是否支持Auto-Save
。
以下示例演示了 Auto-Save
的使用方法:
import (
"github.com/casbin/casbin"
"github.com/casbin/xorm-adapter"
_ "github.com/go-sql-driver/mysql"
)
// enforcer会默认开启AutoSave机制.
a := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
e := casbin.NewEnforcer("examples/basic_model.conf", a)
// 禁用AutoSave机制
e.EnableAutoSave(false)
// 因为禁用了AutoSave,当前策略的改变只在内存中生效
// 这些策略在持久层中仍是不变的
e.AddPolicy(...)
e.RemovePolicy(...)
// 启用自动保存选项。
e.EnableAutoSave(true)
// 因为开启了AutoSave机制,现在内存中的改变会同步回写到持久层中
e.AddPolicy(...)
e.RemovePolicy(...)
For more examples, please see: https://github.com/casbin/xorm-adapter/blob/master/adapter_test.go
如何编写 Adapter
Adapter应实现Adapter 中定义的接口,其中必须实现的为LoadPolicy(model model.Model) error
和SavePolicy(model model.Model) error
。
其他三个函数是可选的。 如果adapter支持Auto-Save
特性,则应该实现它们。
接口名 | 类型 | 描述 |
---|---|---|
LoadPolicy() | 必须 | 从持久层中加载policy规则 |
SavePolicy() | 必须 | 将policy规则保存至持久层 |
AddPolicy() | 可选 | 添加单条policy规则至持久层 |
RemovePolicy() | optional | 从持久层删除单条policy规则 |
RemoveFilteredPolicy() | optional | 从持久层删除符合筛选条件的policy规则 |
如果适配器不支持 自动保存
, 它应该为以下三个可选函数提供一个空实现。 下面是Golang的一个例子:
// AddPolicy 添加一个policy规则至持久层
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}
// RemovePolicy 从持久层删除单条policy规则
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}
// RemoveFilteredPolicy 从持久层删除符合筛选条件的policy规则
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
return errors.New("not implemented")
}
Casbin enforcer在调用这三个可选实现的接口时,会忽略返回的not implemented
异常。
关于如何写入适配器的详细信息。
数据结构 适配器应 最少 支持六列。
数据库名称: 默认数据库名称应该是
casbin
。表格名称 默认表名应该是
casbin_rule
。Ptype 栏。 此列的名称应该是
ptype
而不是p_type
或Ptype
。表定义应该是
(id int priorkey, ptype varchar, v0 varchar, v1 varchar, v2 varchar, v3 varchar, v4 varchar, v5 varchar)
唯一的密钥索引应该建立在列
ptype, v0, v1, v2, v3, v4, v5
上。LoadFilteredPolicy
需要一个filter
作为参数。 Filter应该像这样。{
"p":[ [ "alice" ], [ "bob" ] ],
"g":[ [ "", "book_group" ], [ "", "pen_group" ] ],
"g2":[ [ "alice" ] ]
}
谁负责创建数据库?
我们通常约定,如果相应的数据库结构尚未建立,那么使用adapter作为policy的持久化工具时,它应具有自动创建一个名为 casbin
的数据库的能力。 Please use the Xorm adapter as a reference implementation: https://github.com/casbin/xorm-adapter
Context Adapter
ContextAdapter provides a context-aware interface for Casbin adapters.
Through context, you can implement features such as timeout control for the Adapter API
Example
gormadapter supports adapter with context, the following is a timeout control implemented using context
ca, _ := NewContextAdapter("mysql", "root:@tcp(127.0.0.1:3306)/", "casbin")
// Limited time 300s
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Microsecond)
defer cancel()
err := ca.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"})
if err != nil {
panic(err)
}
How to write an context adapter
ContextAdapter
API only has an extra layer of context processing than ordinary Adapter
API, and on the basis of implementing ordinary Adapter API, you can encapsulate your own processing logic for context
A simple reference to the gormadapter
: context_adapter.go