适配器
在Casbin中,策略存储作为adapter(Casbin的中间件) 实现。 Casbin用户可以使用adapter从存储中加载策略规则 (aka LoadPolicy()
) 或者将策略规则保存到其中 (aka SavePolicy()
)。 为了保持代码轻量级,我们没有把adapter代码放在主库中。
目前支持的适配器列表
Casbin的适配器完整列表如下。 我们欢迎任何第三方对adapter进行新的贡献,如果有请通知我们,我们将把它放在这个列表中:)
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | 对于 CSV (逗号分隔的值) 文件 |
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 |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (内置) | File | Casbin | ❌ | 对于 CSV (逗号分隔的值) 文件 |
Filtered File Adapter (内置) | File | Casbin | ❌ | 对于带策略子集 .CSV (逗号分隔值) 文件加载支持 |
String Adapter (内置) | String | @calebfaruki | ❌ | 用于 String |
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 | @sarneeh and knex | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Knex.js支持 |
Objection.js Adapter | ORM | @willsoto | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Objection.js 支持 |
Node PostgreSQL Native Adapter | SQL | @touchifyapp | ✅ | PostgreSQL adapter with advanced policy subset loading support and improved performances built with node-postgres. |
Mongoose Adapter | NoSQL | elastic.io and Casbin | ✅ | MongoDB is supported by Mongoose |
Node MongoDB Native Adapter | NoSQL | @juicycleff | ✅ | For Node MongoDB Native |
DynamoDB Adapter | NoSQL | @fospitia | ✅ | For Amazon DynamoDB |
Couchbase Adapter | NoSQL | @MarkMYoung | ✅ | For Couchbase |
Redis Adapter | KV store | Casbin | ❌ | For Redis |
Redis Adapter | KV store | @NandaKishorJeripothula | ❌ | For Redis |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Database Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server are supported by techone/database |
Zend Db Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Oracle, IBM DB2, Microsoft SQL Server, Other PDO Driver are supported by zend-db |
Doctrine DBAL Adapter (Recommend) | ORM | Casbin | ✅ | Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management. |
Medoo Adapter | ORM | Casbin | ✅ | 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 Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO, etc. are supported by laminas-db |
Zend-db Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO, etc. are supported by zend-db |
Redis Adapter | KV store | @nsnake | ❌ | For Redis |
适配器 | 类型 | 作者 | 自动保存 | 描述 |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
SQLAlchemy Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by SQLAlchemy |
Async Databases Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by Databases |
Peewee Adapter | ORM | @shblhy | ✅ | PostgreSQL, MySQL, SQLite are supported by Peewee |
MongoEngine Adapter | ORM | @zhangbailong945 | ❌ | MongoDB is supported by MongoEngine |
Couchbase Adapter | NoSQL | ScienceLogic | ✅ (without remove_filtered_policy() ) | For Couchbase |
DynamoDB Adapter | NoSQL | @abqadeer | ✅ | For DynamoDB |
Pymongo Adapter | NoSQL | Casbin | ❌ | MongoDB is supported by Pymongo |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
EF Adapter | ORM | Casbin | ❌ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework 6 |
EFCore Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework Core |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Diesel Adapter | ORM | Casbin | ✅ | SQLite, PostgreSQL, MySQL are supported by Diesel |
Sqlx Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL are supported by Sqlx with fully asynchronous operation |
YAML Adapter | String | Casbin | ✅ | For YAML |
note
- 如果使用显式或隐式adapter调用
casbin.NewEnforcer()
,策略将自动加载。 - 可以调用
e.LoadPolicy()
来从存储中重新加载策略规则。 - 如果adapter不支持
Auto-Save
特性,则在添加或删除策略时不能将策略规则自动保存回存储器。 你必须手动调用SavePolicy()
来保存所有的策略规则
例子
这里我们提供几个例子:
文件适配器 (内置)
以下代码展示了如何通过内置文件适配器初始化一个enforcer:
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?;
它等同于如下代码:
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,密码为空。
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
您可以按照如下所示的方式使用您自定义的适配器:
import (
"github.com/casbin/casbin"
"github.com/your-username/your-repo"
)
a := yourpackage.NewAdapter(params)
e := casbin.NewEnforcer("examples/basic_model.conf", a)
在运行时进行加载或保存配置信息
您可以在初始化后重新加载模型与策略,或保存新的策略:
// 从模型CONF文件重新加载模型。
e.LoadModel()
// 从文件或数据库中重新加载策略。
e.LoadPolicy()
// 保存当前策略 (通常使用 Casbin API更改后) 返回文件或数据库。
e.SavePolicy()
自动保存
自动保存机制 (Auto-Save
) 是适配器的特性之一。 如果当前适配器支持自动保存特性,该适配器可以向存储中添加一个策略规则,或者从存储中移除一个策略规则。 这与SavePolicy()
不同,因为后者将删除存储中的所有策略规则,并将所有策略规则从Casbin enforcer保存到存储中。 因此,当策略规则的数量较多时,使用SavePolicy()
可能会出现性能问题。
当适配器支持自动保存机制时,您可以通过Enforcer.EnableAutoSave()
函数来开启或关闭该机制。 默认情况下启用该选项(如果适配器支持自动保存的话)。
note
Auto-Save
特性是可选的。 Adapter可以选择是否实现它。Auto-Save
只在Casbin enforcer使用的adapter支持它时才有效。- 请参阅上面适配器列表中的
自动保存
列,以查看自动保存
是否有适配器支持。
下面是一个关于如何使用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(...)
// 开启AutoSave机制
e.EnableAutoSave(true)
// 因为开启了AutoSave机制,现在内存中的改变会同步回写到持久层中
e.AddPolicy(...)
e.RemovePolicy(...)
有关更多示例,请参见: 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() | 强制的 | 从存储中加载所有策略规则 |
SavePolicy() | 强制的 | 将所有策略规则保存到存储中 |
AddPolicy() | 可选择的 | 向存储中添加策略规则 |
RemovePolicy() | 可选择的 | 从存储中删除策略规则 |
RemoveFilteredPolicy() | 可选择的 | 从存储中删除匹配筛选器的策略规则 |
note
如果一个适配器不支持Auto-Save
,它应该为以下三个可选函数提供一个空实现。 以下是Golang中的一个样例:
/ AddPolicy 向存储器添加了一条策略规则。
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}
// RemovePolicy 从存储器中移除一条策略规则。
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}
// RemoveFilteredPolicy 从存储器中移除可匹配过滤器的策略规则。
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
return errors.New("not implemented")
}
Casbin enforcer在调用这三个可选实现的接口时,会忽略返回的not implemented
错误。
谁负责创建数据库?
作为约定,adapter应该能够自动创建一个名为casbin
的数据库(如果它不存在的话),并将其用于策略存储。 具体请参考Xorm adapter的实现:https://github.com/casbin/xorm-adapter