首页 > 解决方案 > 如何从 NestJS 的 GraphQL 解析器内部设置会话密钥?

问题描述

我正在发现 Nest.js,我想使用 GraphQL 设置一个基于 cookie 的身份验证系统。

我已经安装了 express-session 中间件,这里是配置:

main.ts

 app.use(
    session({
      store: new redisStore({
        client: redis
      } as any),
      name: 'qid',
      secret: SESSION_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        secure: !isDev,
        maxAge: 1000 * 60 * 60 * 24 * 7 * 365
      }
    })
  )

它工作正常,因为当我这样做时:

 app.use((req: any, res: any, next: any) => {
      // Debug purpose
      req.session.userId = '42'
      next()
    })

cookie 已添加。

现在我有两个突变,registerlogin。在登录突变中(或在 userService 中),在我找到一个用户后,我想做类似的事情,req.session.userId = user.id但我找不到这样做的方法。

我试图添加@Context() ctx到我的突变中。如果我控制台日志 ctx,它包含我期望的所有内容(例如 req.session.id)

但如果我这样做ctx.req.session.userId = 'something'了,cookie 就没有设置!

这是我的突变:

用户解析器.ts

@Mutation('login')
  async login(
    @Args('email') email: string,
    @Args('password') password: string,
    @Context() ctx: any
  ) {
    console.log(ctx.req.session.id) // Show the actual session id
    ctx.req.session.userId = 'something' // Do not set any cookie
    return await this.userService.login(email, password)
  }
}

我完全迷路了,我真的需要帮助,我很想了解发生了什么。我知道我可能做错了,但我对 Nest 和 GraphQL 都是新手。

谢谢你们...

标签: typescriptauthenticationgraphqlnestjs

解决方案


几天后我发现了这个问题......而且它是......

GraphQL Playground -> Settings -> 添加“request.credentials”:“include”(并且没有“omit”)

希望它会帮助某人..


推荐阅读