主要是基于本地存储策略,使用nodejs 的客户端进行认证的试用
环境准备
- docker-compose
version: "3"
services:
cerbos:
image: ghcr.io/cerbos/cerbos:latest
volumes:
- ./policies:/policies
- ./config:/config
command: server --config=/config/conf.yaml
ports:
- "3592:3592"
- "3593:3593"
cerbos-compile:
profiles:
- compile
image: ghcr.io/cerbos/cerbos:latest
volumes:
- ./policies:/policies
command: compile /policies
ports:
- "3594:3592"
- "3595:3593"
- 策略定义
策略说明:定义了一个contact 的资源,同时配置了几种角色的规则策略,同时部分角色的规则使用了条件进行检查
---
apiVersion: api.cerbos.dev/v1
resourcePolicy:
version: default
resource: contact
rules:
# admin 支持所有角色
- actions: ["*"]
effect: EFFECT_ALLOW
roles:
- admin
# 销售部门用户可以进行读取以及创建
- actions: ["read", "create"]
effect: EFFECT_ALLOW
roles:
- user
condition:
match:
expr: request.principal.attr.department == "Sales"
# 用户角色对于更新以及删除,需要主体id 与属性的所有id一致
- actions: ["update", "delete"]
effect: EFFECT_ALLOW
roles:
- user
condition:
match:
expr: request.resource.attr.ownerId == request.principal.id
- nodejs 应用
const { HTTP } = require("@cerbos/http");
const cerbos = new HTTP("http://localhost:3592");
const demo = async function () {
let result = await cerbos.isAllowed({
principal: {
id: "[email protected]",
roles: ["user"],
attr: { department: "Sales" },
},
resource: {
kind: "contact",
id:"333",
attr: { ownerId: "[email protected]" },
},
action: "update",
});
console.log(result)
}
demo()
- 效果
说明
以上是一个简单的测试,就是一个简单的测试,实际上会发现cerbos 使用还是特别方便的,类似的casbin 因为实现了太多的功能,反而弄的比较复杂,使用以及管理上不是特别方便,尤其是需要大规模使用. 亚马逊团推实际上也开源了一个cedar的安全策略引擎,也是不错的,毕竟aws 的iam 实现还是很牛的
参考资料
https://github.com/cerbos/cerbos-sdk-javascript
https://github.com/casbin/casbin
https://github.com/cedar-policy/cedar
https://docs.cedarpolicy.com/