【问题标题】:Access cookie data outside a component访问组件外的 cookie 数据
【发布时间】:2020-11-15 16:33:42
【问题描述】:

我正在使用 Strapi 作为 CMS 和身份验证服务器来构建 Next.js 应用程序。我设法从 auth 端点获取了一个 JWT,并将其存储在一个 cookie 中。要从strapi中检索受保护的内容,我需要send this JWT in the header

我正在使用 Apollo 向 Strapi 发送 graphQL 查询,根据他们的 documentation,我可以通过将其添加到 utils/apollo.js 来轻松设置 auth 标头

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = cookies.get('jwt') <-- This is what I'd like to do, but I can't figure out how to access cookies at this point.
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

如何访问上述应用程序中的 cookie。它不是组件的一部分,尽管它用于构建 HOC?

虽然使用 localstorage 是一种选择,但我了解到 cookie 是一种更安全的数据存储方式。 使用安全的 cookie 不是一个选项 - 我不确定strapi 是否允许它,也因为有多个前端来源 vercel 为所有分支构建预览

【问题讨论】:

    标签: node.js reactjs jwt next.js apollo-client


    【解决方案1】:

    一旦您设置了 cookie,它将在 Cookie 标头中传递,因此您需要从那里检索它,而不是仅在浏览器中可用但在服务器端请求中不可用的 cookies 对象。此外,如果您使用CORS,您将需要在客户端和服务器中都使用enable 凭据,特别是在客户端中您需要设置credentials: 'include'。这是 cookie 工作所必需的设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2014-09-05
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2011-01-31
      • 2018-08-03
      相关资源
      最近更新 更多