背景与价值
授权过宽会导致越权。层级化Scope与精确匹配可按最小权限治理接口访问。
统一规范
- 层级命名:`resource:action`,支持通配 `*` 仅在资源级别配置。
- 最小权限:仅授予必要的动作,拒绝默认无匹配。
- 审计:记录拒绝与越权尝试。
核心实现
Scope匹配
```ts
type Scope = string // e.g., 'users:read', 'users:write', 'posts:*'
function allow(scopes: Scope[], resource: string, action: string): boolean {
const need = resource + ':' + action
const any = resource + ':*'
const set = new Set(scopes)
if (set.has(need)) return true
if (set.has(any)) return true
return false
}
type Token = { scope: Scope[] }
function gate(token: Token, resource: string, action: string): boolean { return allow(token.scope || [], resource, action) }
```
落地建议
- 采用 `resource:action` 的层级命名并仅在资源级支持通配,避免全局通配。
- 默认拒绝无匹配授权;按审计优化Scope分配与接口设计。
验证清单
- 授权是否按 `resource:action` 精确匹配;通配是否仅在资源级别生效。

发表评论 取消回复