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

TypeGraphQL搭配TypeGoose时如何保护字段禁止被GraphQL查询

解决方案

你现在能通过GraphQL查询到password字段的核心原因是:你给该字段添加了@Field()装饰器,TypeGraphQL会默认将所有标记了@Field()的类属性暴露到公开的GraphQL Schema中,调用方自然可以在查询语句中请求该字段。

最直接、性能最好的实现方式就是移除password字段上的@Field()装饰器,修改后的模型代码如下:

@index({ email: 1 })
@queryMethod(findByEmail)
@ObjectType()
export class User {
  @Field(() => String)
  _id: string;

  @Field(() => String)
  @prop({ required: true })
  name: string;

  @Field(() => String)
  @prop({ required: true })
  email: string;

  // 移除@Field装饰器后,该字段不会出现在GraphQL Schema中
  @prop({ required: true })
  password: string;
}

方案说明

  • 移除@Field()后,TypeGraphQL不会将password字段纳入GraphQL类型定义,调用方如果在查询语句中主动请求password字段,会直接在Schema校验阶段被拦截报错,根本不会进入业务逻辑执行流程,从根源上避免敏感字段泄露。
  • 该改动不会对TypeGoose的数据库操作产生任何影响,password字段仍然会正常写入、读取MongoDB,你写的密码哈希校验、登录验证等逻辑完全可以正常读取该字段的值使用。
  • 如果存在极少数需要返回password字段的内部场景(不建议对外暴露),不要直接修改通用User模型,应该单独定义专用的ObjectType返回类,避免权限配置疏漏导致敏感数据泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:18:35