주요 콘텐츠로 건너뛰기

Adapters

Casbin에서 정책 저장소는 어댑터(즉, Casbin의 미들웨어)로 구현됩니다. Casbin 사용자는 어댑터를 사용하여 저장소에서 정책 규칙을 로드(즉, LoadPolicy())하거나 정책 규칙을 저장(즉, SavePolicy())할 수 있습니다. 가벼운 무게를 유지하기 위해, 우리는 어댑터 코드를 주 라이브러리에 넣지 않습니다.

지원되는 어댑터

아래에 Casbin 어댑터의 전체 목록이 제공됩니다. 새로운 어댑터에 대한 제3자의 기여는 환영이며, 우리에게 알려주시면 이 목록에 추가하겠습니다:

AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbinFor .CSV (Comma-Separated Values) files
Filtered File Adapter (built-in)File@faceless-saintFor .CSV (Comma-Separated Values) files with policy subset loading support
SQL AdapterSQL@Blank-XuMySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by database/sql
Xorm AdapterORMCasbinMySQL, PostgreSQL, TiDB, SQLite, SQL Server, Oracle are supported by Xorm
GORM AdapterORMCasbinMySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM
GORM Adapter ExORMCasbinMySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM
Ent AdapterORMCasbinMySQL, MariaDB, PostgreSQL, SQLite, Gremlin-based graph databases are supported by ent ORM
Beego ORM AdapterORMCasbinMySQL, PostgreSQL, Sqlite3 are supported by Beego ORM
SQLX AdapterORM@memweyMySQL, PostgreSQL, SQLite, Oracle are supported by SQLX
Sqlx AdapterORM@Blank-XuMySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by sqlx
GF ORM AdapterORM@vance-liuMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
GoFrame ORM AdapterORM@kotlin2018MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
gf-adapterORM@zcycMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
Gdb AdapterORM@jxo-meMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
GoFrame V2 AdapterORM@hailazMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
Bun AdapterORM@JunNishimuraMySQL, SQLite, PostgreSQL, SQL Server are supported by Bun ORM
Filtered PostgreSQL AdapterSQLCasbinFor PostgreSQL
Filtered pgx AdapterSQL@pckhoiPostgreSQL is supported by pgx
PostgreSQL AdapterSQL@cychiuaeFor PostgreSQL
RQLite AdapterSQLEDOMO SystemsFor RQLite
MongoDB AdapterNoSQLCasbinFor MongoDB based on MongoDB Go Driver
RethinkDB AdapterNoSQL@adityapandey9For RethinkDB
Cassandra AdapterNoSQLCasbinFor Apache Cassandra DB
DynamoDB AdapterNoSQLHOOQFor Amazon DynamoDB
DynacasbinNoSQLNewbMiaoFor Amazon DynamoDB
ArangoDB AdapterNoSQL@adamwasilaFor ArangoDB
Amazon S3 AdapterCloudSolutoFor Minio and Amazon S3
Go CDK AdapterCloud@bartventerAdapter based on Go Cloud Dev Kit that supports: Amazon DynamoDB, Azure CosmosDB, GCP Firestore, MongoDB, In-Memory
Azure Cosmos DB AdapterCloud@spacycoderFor Microsoft Azure Cosmos DB
GCP Firestore AdapterCloud@reedomFor Google Cloud Platform Firestore
GCP Cloud Storage AdapterCloudquramiFor Google Cloud Platform Cloud Storage
GCP Cloud Spanner AdapterCloud@flowerinthenightFor Google Cloud Platform Cloud Spanner
Consul AdapterKV store@ankitm123For HashiCorp Consul
Redis Adapter (Redigo)KV storeCasbinFor Redis
Redis Adapter (go-redis)KV store@mlsenFor Redis
Etcd AdapterKV store@sebastianliuFor etcd
BoltDB AdapterKV store@spezaFor Bolt
Bolt AdapterKV store@wirepairFor Bolt
BadgerDB AdapterKV store@initsFor BadgerDB
Protobuf AdapterStreamCasbinFor Google Protocol Buffers
JSON AdapterStringCasbinFor JSON
String AdapterString@qiangmzsxFor String
HTTP File AdapterHTTP@h4ckednekoFor http.FileSystem
FileSystem AdapterFile@nauconFor fs.FS and embed.FS
노트
  1. casbin.NewEnforcer()가 명시적 또는 암시적 어댑터와 함께 호출되면, 정책이 자동으로 로드됩니다.
  2. 저장소에서 정책 규칙을 다시 로드하기 위해 e.LoadPolicy()를 호출할 수 있습니다.
  3. 어댑터가 Auto-Save 기능을 지원하지 않는 경우, 정책을 추가하거나 제거할 때 정책 규칙이 자동으로 저장소로 다시 저장되지 않습니다. 모든 정책 규칙을 저장하기 위해 SavePolicy()를 수동으로 호출해야 합니다.

예시

다음은 몇 가지 예시를 제공합니다:

파일 어댑터 (내장형)

아래는 내장 파일 어댑터에서 강제 실행기를 초기화하는 방법을 보여줍니다:

import "github.com/casbin/casbin"

e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")

이것은 다음과 같습니다:

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)

MySQL 어댑터

아래는 MySQL 데이터베이스에서 강제 실행기를 초기화하는 방법을 보여줍니다. 이것은 127.0.0.1:3306에서 root와 빈 비밀번호로 MySQL DB에 연결합니다.

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)

자체 저장소 어댑터 사용

아래와 같이 자체 어댑터를 사용할 수 있습니다:

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로 어댑터를 변환하려면 다음과 같이 할 수 있습니다:

1.A에서 메모리로 정책 로드

e, _ := NewEnforcer(m, A)

또는

e.SetAdapter(A)
e.LoadPolicy()

2.A에서 B로 어댑터 변환

e.SetAdapter(B)

3.메모리에서 B로 정책 저장

e.SavePolicy()

런타임에 로드/저장

초기화 후에 모델을 다시 로드하거나 정책을 다시 로드하거나 정책을 저장하려는 경우도 있을 수 있습니다:

// 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

어댑터에는 Auto-Save라는 기능이 있습니다. 어댑터가 Auto-Save를 지원하면, 저장소에 단일 정책 규칙을 추가하거나 저장소에서 단일 정책 규칙을 제거하는 것을 지원할 수 있음을 의미합니다. 이는 SavePolicy()와는 다르며, 후자는 저장소의 모든 정책 규칙을 삭제하고 Casbin enforcer의 모든 정책 규칙을 저장소에 저장합니다. 따라서 정책 규칙의 수가 많을 경우 성능 문제가 발생할 수 있습니다.

어댑터가 Auto-Save를 지원할 때, Enforcer.EnableAutoSave() 함수를 통해 이 옵션을 전환할 수 있습니다. 이 옵션은 기본적으로 활성화되어 있습니다(어댑터가 지원하는 경우).

노트
  1. Auto-Save 기능은 선택 사항입니다. 어댑터는 이를 구현하거나 구현하지 않을 수 있습니다.
  2. Auto-Save는 어댑터가 지원할 때만 Casbin enforcer에 대해 작동합니다.
  3. 어댑터가 Auto-Save를 지원하는지 확인하려면 위의 어댑터 목록에서 AutoSave 열을 참조하십시오.

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

더 많은 예제를 보려면 다음을 참조하십시오: https://github.com/casbin/xorm-adapter/blob/master/adapter_test.go

어댑터 작성 방법

모든 어댑터는 적어도 두 가지 필수 메서드인 LoadPolicy(model model.Model) errorSavePolicy(model model.Model) error를 제공하여 Adapter 인터페이스를 구현해야 합니다.

나머지 세 가지 함수는 선택 사항입니다. 어댑터가 Auto-Save 기능을 지원하는 경우 이들을 구현해야 합니다.

메서드유형설명
LoadPolicy()필수저장소에서 모든 정책 규칙을 로드합니다
SavePolicy()필수모든 정책 규칙을 저장소에 저장합니다
AddPolicy()선택저장소에 정책 규칙을 추가합니다
RemovePolicy()선택저장소에서 정책 규칙을 제거하십시오
RemoveFilteredPolicy()선택 사항필터와 일치하는 정책 규칙을 저장소에서 제거하십시오
노트

어댑터가 'Auto-Save'를 지원하지 않는 경우, 세 가지 선택적 함수에 대해 빈 구현을 제공해야 합니다. 다음은 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는 이 세 가지 선택적 함수를 호출할 때 'not implemented' 오류를 무시합니다.

어댑터를 작성하는 방법에 대한 세부 정보가 있습니다.

  • 데이터 구조. 어댑터는 최소한 여섯 개의 열을 읽을 수 있어야 합니다.
  • 데이터베이스 이름. 기본 데이터베이스 이름은 'casbin'이어야 합니다.
  • 테이블 이름. 기본 테이블 이름은 'casbin_rule'이어야 합니다.
  • Ptype 열. 이 열의 이름은 'p_type' 또는 'Ptype' 대신 'ptype'이어야 합니다.
  • 테이블 정의는 '(id int primary key, ptype varchar, v0 varchar, v1 varchar, v2 varchar, v3 varchar, v4 varchar, v5 varchar)'이어야 합니다.
  • 고유 키 인덱스는 'ptype,v0,v1,v2,v3,v4,v5' 열에 구축되어야 합니다.
  • LoadFilteredPolicyfilter를 매개변수로 필요로 합니다. 필터는 이런 식이어야 합니다.
{
"p":[ [ "alice" ], [ "bob" ] ],
"g":[ [ "", "book_group" ], [ "", "pen_group" ] ],
"g2":[ [ "alice" ] ]
}

데이터베이스를 생성할 책임이 누구인가요?

관례적으로, 어댑터는 존재하지 않는 경우 'casbin'이라는 데이터베이스를 자동으로 생성하고 정책 저장소로 사용할 수 있어야 합니다. 참조 구현으로 Xorm 어댑터를 사용하십시오: https://github.com/casbin/xorm-adapter

컨텍스트 어댑터

ContextAdapter는 Casbin 어댑터에 대한 컨텍스트 인식 인터페이스를 제공합니다.

컨텍스트를 통해 어댑터 API에 대한 타임아웃 제어와 같은 기능을 구현할 수 있습니다

예시

gormadapter는 컨텍스트가 있는 어댑터를 지원하며, 다음은 컨텍스트를 사용하여 구현된 타임아웃 제어입니다

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

컨텍스트 어댑터를 작성하는 방법

ContextAdapter API는 일반 Adapter API보다 컨텍스트 처리 계층만 추가로 있으며, 일반 Adapter API를 구현하는 기반 위에 컨텍스트에 대한 자체 처리 로직을 캡슐화할 수 있습니다

간단한 gormadapter에 대한 참조: context_adapter.go