当前位置: 首页 > 文档资料 > Casbin 中文文档 >

适配器

优质
小牛编辑
133浏览
2023-12-01

在Casbin中,策略存储作为adapter(Casbin的中间件) 实现。 Casbin用户可以使用adapter从存储中加载策略规则 (aka LoadPolicy()) 或者将策略规则保存到其中 (aka SavePolicy())。 为了保持代码轻量级,我们没有把adapter代码放在主库中。

目前支持的适配器列表

Casbin的适配器完整列表如下。 我们欢迎任何第三方对adapter进行新的贡献,如果有请通知我们,我们将把它放在这个列表中:)

GoJavaNode.jsPHPPython.NETRustRubySwiftLua
适配器类型作者自动保存描述
File Adapter (内置)FileCasbinnoFor .CSV (Comma-Separated Values) files
Filtered File Adapter (内置)File@faceless-saintno对于 CSV (逗号分隔的值) 个带策略子集加载支持的文件
SQL AdapterSQL@Blank-XuyesMySQL,PostgreSQL,SQL Server和SQLite3在 master分支中受到database/sql的支持,Oacle在 oracle分支中也受到database/sql的支持
Xorm AdapterORMCasbinyes通过 Xorm实现,支持MySQL, PostgreSQL, Sqlite3, SQL Server等多种存储引擎的adapter
Gorm AdapterORMCasbinyes通过 Gorm实现,支持MySQL, PostgreSQL, Sqlite3, SQL Server等多种存储引擎的adapter
Ent AdapterORMCasbinyesMySQL, MariaDB, PostgreSQL, SQLite, 基于Gremlin的图数据库由 [ent ORM](https://entgo. io/) 支持。
Beego ORM AdapterORMCasbinyesMySQL, PostgreSQL, Sqlite3 由 Beego ORM 支持
SQLX AdapterORM@memweyyesMySQL, PostgreSQL, SQLite, Oracle 由 SQLX 支持
Sqlx AdapterSQL@Blank-XuyesMySQL, PostgreSQL, SQL Server, SQLite3 由 master 分支支持,Oracle由oracle 分支受到sqlx的支持
GF ORM AdapterORM@vance-liuyesMySQL, SQLite, PostgreSQL, Oracle, SQL Server 受到 GoFrame ORM 的支持
GoFrame ORM AdapterORM@kotlin2018yesMySQL, SQLite, PostgreSQL, Oracle, SQL Server由GoFrame ORM支持
Filtered PostgreSQL AdapterSQLCasbinyes针对 PostgreSQL
PostgreSQL AdapterSQL@cychiuaeyes用于PostgreSQL
RQLite AdapterSQLEDOMO Systemsyes用于RQLite
MongoDB AdapterNoSQLCasbinyes基于 MongoDB Go Driver 用于 MongoDB
RethinkDB AdapterNoSQL@adityapandey9yes用于RethinkDB
Cassandra AdapterNoSQLCasbinno用于Apache Cassandra DB
DynamoDB AdapterNoSQLHOOQno用于Amazon DynamoDB
DynacasbinNoSQLNewbMiaoyes用于Amazon DynamoDB
ArangoDB AdapterNoSQL@adamwasilayes用于ArangoDB
Amazon S3 AdapterCloudSolutono用于MinioAmazon S3
Azure Cosmos DB AdapterCloud@spacycoderyes用于Microsoft Azure Cosmos DB
GCP Firestore AdapterCloud@reedomno用于Google Cloud Platform Firestore
GCP Cloud Storage AdapterCloudquramino用于Google Cloud Platform Cloud Storage
GCP Cloud Storage Adapter@flowerinthenightyes用于Google Cloud Platform Cloud Spanner
Consul AdapterKV store@ankitm123no用于HashiCorp Consul
Redis 适配器 (Redigo)KV storeCasbinyes用于Redis
Redis Adapter (go-redis)KV store@mlsenyes用于Redis
Etcd 适配器KV store@sebastianliuno用于etcd
BoltDB AdapterKV store@spezayes用于Bolt
Bolt AdapterKV store@wirepairno用于Bolt
BadgerDB AdapterKV store@initsyes用于BadgerDB
Protobuf AdapterStreamCasbinno用于 Google Protocol Buffers
JSON AdapterStringCasbinno用于JSON
String AdapterString@qiangmzsxno用于字符串
HTTP File AdapterHTTP@h4ckednekono用于http.FileSystem
FileSystem AdapterFile@nauconnoFor fs.FS and embed.FS
适配器类型作者自动保存描述
File Adapter (内置)FileCasbinno对于 CSV (逗号分隔的值) 文件
JDBC AdapterJDBCCasbinyesMySQL, Oracle, PostgreSQL, DB2, Sybase, SQL 服务器由 JDBC 支持
Hibernate AdapterORMCasbinyesOracle, DB2, SQL Server, Sybase, MySQL, PostgreSQL 由 Hibernate支持
MyBatis AdapterORMCasbinyesMySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server (与 JDBC 相同) 由 MyBatis 3 支持
Hutool AdapterORM@mapleafgoyesMySQL, Oracle, PostgreSQL, SQLite 由 Hutool 支持
MongoDB AdapterNoSQLCasbinyesMongoDB 由 Mongodb-driver-sync 支持
DynamoDB AdapterNoSQLCasbinno对于 Amazon DynamoDB
Redis AdapterKV storeCasbinyes用于 Redis
适配器类型作者自动保存描述
File Adapter (内置)FileCasbinno对于 CSV (逗号分隔的值) 文件
Filtered File Adapter (内置)FileCasbinno对于带策略子集 .CSV (逗号分隔值) 文件加载支持
String Adapter (内置)String@calebfarukino用于 String
Basic AdapterNative ORMCasbinyespg, mysql, mysql2, sqlite3, oracedb, mssql 是适配器本身支持的
Sequelize AdapterORMCasbinyesMySQL、 PostgreSQL、 SQLite、 Microsoft SQL Server 由 Sequelize 支持
TypeORM AdapterORMCasbinyesMySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL, MongoDB 由 TypeORM 支持
Prisma AdapterORMCasbinyesMySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, AWS Aurora, Azure SQL 由 Prisma支持
Knex AdapterORM@sarneeh and knexyesMSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Knex.js支持
Objection.js AdapterORM@willsotoyesMSSQL, MySQL, PostgreSQL, SQLite3, Oracle 由 Objection.js 支持
Node PostgreSQL Native AdapterSQL@touchifyappyesPostgreSQL 适配器,拥有高级策略子集加载支持以及由 [node-postgres](https://node-postgres. com/) 构建的更好的性能。
MongoDB AdapterNoSQLelastic.io 和 CasbinyesMongoDB 由 Mongoose 支持
Mongoose 适配器 (无交易)NoSQLminhducckyesMongoDB 由 Mongoose 支持
Node MongoDB 原生 AdapterNoSQL@juicycleffyes用于 Node MongoDB Native
DynamoDB AdapterNoSQL@fospitiayes用于Amazon DynamoDB
Couchbase AdapterNoSQL@MarkMYoungyes用于 Couchbase
Redis AdapterKV storeCasbinno用于 Redis
Redis AdapterKV store@NandaKishorJeripothulano用于 Redis
适配器类型作者自动保存描述
文件适配器 (内置)FileCasbinno用于 .CSV (Comma-Separated Values) 文件
数据库适配器ORMCasbinyesMySQL, PostgreSQL, SQLite, Microsoft SQL Server 由 techone/database 支持
Zend Db 适配器ORMCasbinyesMySQL, PostgreSQL, SQLite, Oracle, IBM DB2, Microsoft SQL Server, 其他 PDO Driver 由 zend-db 支持
Doctrine DBAL 适配器(建议)ORMCasbinyes强大的 PHP 数据库抽象层(DBAL),具有数据库架构内省和管理的许多功能。
Medoo 适配器ORMCasbinyesMedoo 是一个用来加速开发的轻量PHP 数据库框架。 支持所有 SQL 数据库,包括 MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle 以及更多。
Laminas-db 适配器ORMCasbinyesMySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO等。 由 laminas-db 支持
Zend-db 适配器ORMCasbinyesMySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO等。 由 zend-db 支持
Redis 适配器KV store@nsnakeno用于 Redis
适配器类型作者自动保存描述
文件适配器(内置)FileCasbinno对于 CSV 文件
SQLAlchemy 适配器ORMCasbinyesPostgreSQL、MySQLite、Oracle、Microsoft SQL Server、Firebird、Sybase 由 SQLAlchemy 支持
异步数据库适配器ORMsampingantechyesPostgreSQL、MySQLite、Oracle、Microsoft SQL Server、Firebird、Sybase 由 Databases 支持。
Peewee 适配器ORM@shblhyyesPostgreSQL、 MySQL、 SQLite 由 Peewee 支持
MongoEngine 适配器ORM@zhangbailong945noMongoDB 由 MongoEngine 支持
Pony ORM AdapterORM@drorvinkleryesMySQL, PostgreSQL, SQLite, Oracle, CockroachDB由Pony ORM支持
Tortoise ORM AdapterORM@thearchitectoryesPostgreSQL (>=9.4), MySQL, MariaDB, 和 SQLite 都由 Tortoise ORM 支持
Couchbase AdapterNoSQLScienceLogicyes (没有 remove_filtered_policy())用于 Couchbase
DynamoDB AdapterNoSQL@abqadeeryes用于 DynamoDB
Pymongo 适配器NoSQLCasbinnoMongoDB 由 [Pymongo 支持](https://pypi. org/project/pymongo/)
适配器类型作者自动保存机制说明
文件适配器 (内置)FileCasbinno用于 .CSV 文件
EF 适配器ORMCasbinnoMySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, 等等 由 [Entity Framework 6](https://docs. microsoft. com/en-us/ef/ef6/) 支持
EFCore 适配器ORMCasbinyesMySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, 等等. 由 Entity Framework Core 支持
EFCore 适配器 (.NET Core 5)ORM@g4dvaliyesMySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, 等等 由 Entity Framework Core 支持
适配器类型作者自动保存机制说明
文件适配器 (内置)FileCasbinno用于 .CSV 文件
Diesel 适配器ORMCasbinyesSQLite, PostgreSQL, MySQLDiesel 支持
Sqlx 适配器ORMCasbinyesPostgreSQL, MySQL 由 Sqlx 支持,可实现完全异步操作
JSON AdapterStringCasbinyes用于JSON
YAML Adapter字符串Casbinyes用于 YAML
Adapter类型作者自动保存描述
File Adapter (内置)文件Casbinno用于 .CSV (Comma-Separated Values) 文件
Sequelize AdapterORMCasbinRubyyesADO, Amalgalite, IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle, PostgreSQL, SQLAnywhere SQLite3, 和 TinyTDS 都由 Sequel 支持
Adapter类型作者自动保存描述
File Adapter (内置)FileCasbinno用于 .CSV (Comma-Separated Values) 文件
Memory Adapter (内置)内存Casbinno用于内存
Fluent AdapterORMCasbinyesPostgreSQL、SQLite、MySQL、MongoDBFluent 支持
AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbinnoFor .CSV (Comma-Separated Values) files
Filtered File Adapter (built-in)FileCasbinnoFor .CSV (Comma-Separated Values) files with policy subset loading support
LuaSQL AdapterORMCasbinyesMySQL, PostgreSQL, SQLite3 are supported by LuaSQL
4DaysORM AdapterORMCasbinyesMySQL, SQLite3 are supported by 4DaysORM
note
  1. 如果使用显式或隐式adapter调用casbin.NewEnforcer(),策略将自动加载。
  2. 可以调用e.LoadPolicy() 来从存储中重新加载策略规则。
  3. 如果adapter不支持Auto-Save特性,则在添加或删除策略时不能将策略规则自动保存回存储器。 你必须手动调用 SavePolicy() 来保存所有的策略规则

例子

Here we provide several examples:

文件适配器 (内置)

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

GoPHPRust
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:

GoPHPRust
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 适配器

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.

GoRustPHP
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

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)

Migrate/Convert between different adapter

If you want to convert adapter from A to B, you can do like this:

  1. Load policy from A to memory
   e, _ := NewEnforcer(m, A)

or

e.SetAdapter(A)
e.LoadPolicy()
  1. convert your adapter from A to B

    e.SetAdapter(B)
    
  2. Save policy from memory to B

    e.LoadPolicy()
    

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

自动保存

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

// 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(...)

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

如何编写 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.

方法类型描述
LoadPolicy()强制的从存储中加载所有策略规则
SavePolicy()强制的将所有策略规则保存到存储中
AddPolicy()可选择的向存储中添加策略规则
RemovePolicy()可选择的从存储中删除策略规则
RemoveFilteredPolicy()可选择的从存储中删除匹配筛选器的策略规则
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 向存储器添加了一条策略规则。
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 will ignore the not implemented error when calling these three optional functions.

There're details about how to write an adapter.

  • 数据结构 适配器应 最少 支持六列。
  • 数据库名称: 默认数据库名称应该是 cassbin
  • 表格名称 默认表名应该是 casbin_rule
  • Ptype 栏。 此列的名称应该是 ptype 而不是 p_typePtype
  • 表定义应该是 (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应该像这样。 json { "p":[ [ "alice" ], [ "bob" ] ], "g":[ [ "", "book_group" ], [ "", "pen_group" ] ], "g2":[ [ "alice" ] ] }

谁负责创建数据库?

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

← 政策子集加载观察者 →