fly:casbin实现api的访问控制

275 阅读2分钟

是什么?

Casbin是一套规则,定义了acl、rbac、abac等各类访问控制模型,它有各种语言实现,其中 是golang对其的实现

怎么用?

  1. 定义模型model
  2. 预先准备策略
  3. 请求时,如果请求特征,符号预定义的模型,且有相应的策略和其匹配,那么该请求就可以被通过,

一个acl model的示例

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

再定义相应的策略条目

p, alice, data1, read
p, bob, data2, write

那么:

用户alice,是read,data1对象时允许; 用户bob,write,data2对象时允许 除此之外,全部拒绝!

通用使用流程

  1. 实例化一个Enforcer,需要model文件和policy文件的2个文件路径作为参数
e, _ := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
  1. 业务代码使用

sub := "alice" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.

if res, _ := e.Enforce(sub, obj, act); res {
    // permit alice to read data1
} else {
    // deny the request, show an error
}

使用时:casbin从数据表加载policy而非文件,从字符串加载model而非文件

	// 1、从现有*gorm.DB实例,得到一个Adapter
	Apter, err := gormAdapter.NewAdapterByDBUsePrefix(db, prefix)
	if err != nil {
		panic(err)
	}
	// 2、从字符串加载得到model 
	m, err := model.NewModelFromString(text)
	if err != nil {
		panic(err)
	}
	// 3、用model和Adapter实例,实例化一个Enforcer
	e, err := casbin.NewSyncedEnforcer(m, Apter)
	if err != nil {
		panic(err)
	}
	// 4、载入策略 
	err = e.LoadPolicy()
	if err != nil {
		panic(err)
	}

记录日志

如果要记录相应的日志:


	log.SetLogger(&Logger{})
	e.EnableLog(true)

其中SetLogger的参数,需要实现了casbin中的接口


// Logger is the logging interface implementation.
type Logger interface {
	//EnableLog controls whether print the message.
	EnableLog(bool)

	//IsEnabled returns if logger is enabled.
	IsEnabled() bool

	//Print formats using the default formats for its operands and logs the message.
	Print(...interface{})

	//Printf formats according to a format specifier and logs the message.
	Printf(string, ...interface{})
}