---
title: API授权Scope最小权限治理(层级/匹配)最佳实践
keywords:
- Scope
- 最小权限
- 层级匹配
- 授权校验
- 资源动作
description: 通过层级化Scope与资源-动作匹配、最小权限原则与拒绝默认策略,统一治理API授权并降低越权风险。
categories:
- 文章资讯
- 技术教程
---
背景与价值
授权过宽会导致越权。层级化Scope与精确匹配可按最小权限治理接口访问。
统一规范
- 层级命名:
resource:action,支持通配*仅在资源级别配置。 - 最小权限:仅授予必要的动作,拒绝默认无匹配。
- 审计:记录拒绝与越权尝试。
核心实现
Scope匹配
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精确匹配;通配是否仅在资源级别生效。

发表评论 取消回复