简体   繁体   English

如何在NestJS中的GraphQL解析器内部设置会话密钥?

[英]How can I set a session key from inside a GraphQL resolver in NestJS?

I'm discovering Nest.js and I want to setup a cookie based authentication system with GraphQL. 我发现Nest.js,并且想使用GraphQL设置基于cookie的身份验证系统。

I already installed express-session middleware, here is the configuration: 我已经安装了快速会话中间件,这是配置:

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
      }
    })
  )

it works fine because when I do : 它工作正常,因为当我这样做时:

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

The cookie is added. Cookie已添加。

Right now I have two mutations, register and login . 现在,我有两个变体, 注册登录 In the login mutation (or in the userService), after I found a user I want to do something like req.session.userId = user.id but I can't find a way to do this. 在登录突变(或在userService中)中,找到用户后,我想执行类似req.session.userId = user.id但找不到解决方法。

I tried to add @Context() ctx to my mutation. 我试图将@Context() ctx添加到我的突变中。 If I console log ctx, it contains everything I expect (req.session.id for example) 如果我使用控制台ctx,它将包含我期望的所有内容(例如req.session.id)

But if I do ctx.req.session.userId = 'something' , the cookie is not set! 但是,如果我执行ctx.req.session.userId = 'something' ,则未设置cookie!

Here is my mutation: 这是我的突变:

user.resolver.ts user.resolver.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)
  }
}

I am totally lost and I really need help, I'd love to understand what's happening. 我完全迷路了,我真的需要帮助,我很想了解发生了什么。 I know I'm probably doing this totally wrong but I'm new to both Nest and GraphQL.. 我知道我可能完全错了,但是Nest和GraphQL都是新手。

Thank you guys... 感谢大伙们...

I found the problem after many days ... and it was... 许多天后我发现了问题...这是...

GraphQL Playground -> Settings -> add "request.credentials": "include" (and no "omit") GraphQL Playground->设置->添加“ request.credentials”:“ include”(不包括“忽略”)

Hope it will help someone.. 希望对别人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM