# API网关安全与多租户隔离最佳实践
## 概述
API网关作为统一入口需承担身份认证、授权与流量治理职责。通过租户维度的策略与配额,可在多租户场景下保证隔离与公平使用。
## 策略引擎
```typescript
type GatewayContext = { tenantId: string; route: string; method: string; scopes: string[]; ip: string }
type Decision = { allow: boolean; reasons?: string[] }
class GatewayPolicy {
private routeWhitelist: Record = {
GET: ['/health', '/status']
}
evaluate(ctx: GatewayContext): Decision {
const reasons: string[] = []
if (this.isWhitelisted(ctx)) return { allow: true }
if (!this.hasScope(ctx)) { reasons.push('scope_missing'); return { allow: false, reasons } }
return { allow: true }
}
private isWhitelisted(ctx: GatewayContext): boolean {
const list = this.routeWhitelist[ctx.method] || []
return list.includes(ctx.route)
}
private hasScope(ctx: GatewayContext): boolean {
const required = this.requiredScope(ctx.route, ctx.method)
return required ? ctx.scopes.includes(required) : true
}
private requiredScope(route: string, method: string): string | null {
const key = `${method}:${route}`
const map: Record = {
'POST:/orders': 'orders:write',
'GET:/orders': 'orders:read'
}
return map[key] || null
}
}
```
## 租户配额与速率限制
```typescript
class TenantLimiter {
private hits = new Map()
constructor(private windowMs: number, private maxPerWindow: number) {}
allow(tenantId: string): boolean {
const now = Date.now()
const arr = (this.hits.get(tenantId) || []).filter(t => now - t < this.windowMs)
if (arr.length >= this.maxPerWindow) return false
arr.push(now)
this.hits.set(tenantId, arr)
return true
}
}
```
## 认证与JWT作用域
```typescript
type JwtPayload = { sub: string; tenant: string; scope: string[]; exp: number }
function extractCtxFromJwt(token: string): GatewayContext {
const payload = decodeJwt(token) as JwtPayload
return { tenantId: payload.tenant, route: '', method: '', scopes: payload.scope, ip: '' }
}
```
## 上游mTLS与零信任
- 网关到上游服务启用mTLS,双向证书验证
- 按服务标识与租户标签进行细粒度访问控制
## 运维要点
- 路由白名单与作用域映射统一在策略引擎管理
- 速率限制按租户与端点维度配置,监控拒绝率与误杀率
- 启用mTLS与服务身份,形成入口到上游的零信任链路
通过策略引擎、租户速率与mTLS协同,可在复杂多租户场景下实现稳健的网关安全隔离。
发表评论 取消回复