You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GraphQL Viewer模式下安全获取认证用户指定ID的单张图片

错误根因

你之前的写法中@find指令默认是对Image模型做全局查询,不会自动绑定当前User的关联范围,所以任意登录用户都可以查询到所有用户的图片。你混用@find和@whereAuth报错,是因为@whereAuth没有匹配到正确的关联定义,导致调用关联方法时对象为空。

正确实现方案

Lighthouse 的@find指令支持relation参数,指定从父模型的对应关联中查询数据,会自动加上关联外键的过滤条件,天然保证数据权限:

type User {
  name: String!
  images: [Image] @hasMany

  "Fetch image by its ID belonging to the current user"
  image(id: ID @eq): Image @find(relation: "images")
}

这里relation: "images"就是指定从当前User模型的images关联里查找匹配ID的记录,自动会加上user_id = 当前用户ID的查询条件,完全避免越权访问问题。

验证逻辑

你的原有查询语句不需要修改:

{
  me {
    image(id: 4) {
      id
      url
    }
  }
}

如果ID为4的图片不属于当前登录用户,接口会直接返回null,如果需要不存在时抛出404异常,把字段定义改成image(id: ID @eq): Image! @find(relation: "images")即可。

内容的提问来源于stack exchange,提问作者Daniel Loureiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:00