---

title: GraphQL授权与字段级访问控制实施指南

keywords:

  • GraphQL
  • 字段级授权
  • RBAC
  • ABAC
  • Directive
  • 复杂度限制

description: 通过指令与中间层评估,实现GraphQL字段与类型级的授权控制,结合RBAC与ABAC策略与复杂度治理的可落地方案。

categories:

  • 文章资讯
  • 技术教程

---

GraphQL授权与字段级访问控制实施指南

概述

在GraphQL中需要对字段与类型实施细粒度授权。通过指令与中间层评估可实现统一的访问控制。

指令设计

directive @auth(
  role: String,
  permission: String
) on FIELD_DEFINITION | OBJECT

中间层评估

type Context = { userId: string; roles: string[]; permissions: string[] }

function hasRole(ctx: Context, role?: string): boolean {
  return role ? ctx.roles.includes(role) : true
}

function hasPermission(ctx: Context, perm?: string): boolean {
  return perm ? ctx.permissions.includes(perm) : true
}

function evaluateAuth(ctx: Context, args: { role?: string; permission?: string }): boolean {
  return hasRole(ctx, args.role) && hasPermission(ctx, args.permission)
}

字段包装

function wrapResolver(resolver: Function, guard: (ctx: any) => boolean): Function {
  return async (parent: any, args: any, ctx: any, info: any) => {
    if (!guard(ctx)) throw new Error('forbidden')
    return resolver(parent, args, ctx, info)
  }
}

示例

type Query {
  user(id: ID!): User @auth(permission: "users:read")
}

type User @auth(role: "admin") {
  id: ID!
  email: String
  profile: String
}

复杂度治理

function limitComplexity(cost: number, max: number): void {
  if (cost > max) throw new Error('complexity_exceeded')
}

运维要点

  • 将授权策略与Schema正交,使用指令与包装器强制执行
  • 按字段与类型记录授权拒绝与复杂度超限事件
  • 在CI对Schema变化进行授权标注检查

通过指令与统一评估,可实现GraphQL字段级的可验证授权控制。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部