【问题标题】:Sending JWT RefreshToken as Set-Cookie将 JWT RefreshToken 作为 Set-Cookie 发送
【发布时间】:2020-03-12 10:21:27
【问题描述】:

关于将 JWT 刷新令牌设置为 cookie 时正确或错误的简短问题。

如果我的 API 将其响应标头中的 refresh token 发送到 ApolloServer,那么 Set-Cookie 标头将通过我的 Apollo-server 自动传递到客户端(apollo-client)。或者我是否应该期望我的 API 中只有一个正文数据集,包括令牌 + refreshToke,我将通过 apollo-server 中间件提取它作为 cookie 自己附加到客户端响应中。

有什么想法或建议吗?

【问题讨论】:

    标签: api cookies jwt apollo-client apollo-server


    【解决方案1】:

    Cookies 必须由服务器设置。这将使用这样的快速响应对象来完成。确保它可以从您的 gql 上下文中访问。

    res.cookie('X-Refresh-Token', refreshToken, {
      maxAge: 900000,    // 15 minutes in milliseconds
      httpOnly: true,    // ensure the cookie will not be exposed
      secure: true,      // set this in production to ensure HTTPS
      sameOrigin: 'none' // set this in production if the server is separate domain
    })
    

    然后,您的客户端必须启用凭据。对于 apollo-boost,这将是:

    new ApolloClient({
      uri: 'http://localhost:8080',
      credentials: 'include', // 'same-origin' if your server is same domain
    })
    

    为了确保 Cookie 在 GraphQL Playground 中传递:

    new ApolloServer({
      context: ({ req, res }) => ({ req, res }),
      playground: {
        settings: {
          'request.credentials': 'include',
        },
      },
    })
    

    如果您还没有使用它,cookie parser middleware 可能会派上用场。

    【讨论】:

    • 那么,x-refresh-token 需要通过 API 与 Set-Cookie 标头一起发送到 apollo-server,然后将其推送到客户端?
    • 基本上,是的。 apollo-server 本质上只是 express 中间件。通过使用快速响应对象,您应该能够像这样设置 cookie。
    猜你喜欢
    • 2022-08-21
    • 2021-11-16
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多