【问题标题】:Asynchronously generating Bearer token in `gatsby-source-graphql` headers option在“gatsby-source-graphql”标头选项中异步生成承载令牌
【发布时间】:2021-10-04 14:24:30
【问题描述】:

我想在gatsby-source-graphq 标头选项中异步生成Auth token。根据文档,我可以使用异步函数来生成我的Bearer token,但我也想将它存储在某个地方。我无法使用sessionStoragelocalStorage,因为我无权访问gatsby-config.js 中的窗口对象。有什么办法可以做到这一点?这是我的代码:

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
});

const axios = require("axios");

const getAuthToken = async () => {
  const token = btoa(
    `${process.env.CTP_CLIENT_ID}:${process.env.CTP_CLIENT_SECRET}`
  );
  try {
    const { data } = await axios.post(
      // I would like to save the Auth token here
      `${process.env.CTP_AUTH_URL}/oauth/token?grant_type=client_credentials`,
      null,
      {
        headers: {
          Authorization: `Basic ${token}`,
        },
      }
    );
    return `Bearer ${data.access_token}`;
  } catch (err) {
    console.warn(err);
  }
};

module.exports = {
  siteMetadata: {
    siteUrl: "https://www.yourdomain.tld",
    title: "test_shop",
  },
  plugins: [
    "gatsby-plugin-typescript",
    "gatsby-plugin-postcss",
    "gatsby-plugin-image",
    {
      resolve: "gatsby-plugin-google-analytics",
      options: {
        trackingId: "test_shop",
      },
    },
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    {
      resolve: "gatsby-source-graphql",
      options: {
        // Arbitrary name for the remote schema Query type
        typeName: "Merchant",
        // Field under which the remote schema will be accessible. You'll use this in your Gatsby query
        fieldName: "merchant",
        // Url to query from
        url: "https://api.europe-west1.gcp.commercetools.com/wj_trial/graphql",
        // TODO: add token dynamically
        headers: async () => {
          return {
            Authorization: await getAuthToken(),
          };
        },
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: "./src/images/",
      },
      __key: "images",
    },
  ],
};

【问题讨论】:

    标签: graphql config gatsby gatsby-plugin


    【解决方案1】:

    我不认为这是可以实现的,也不是一个好的选择。实际上,您正在 SSR 中获取令牌(当触发 gatsby-source-graphql 时),正如您所指出的,您没有任何工具可用于存储响应。在构建/部署项目时,您(或您的公司/客户)将始终触发此操作。

    在您的客户端(任何 React 组件)中,您知道任何 AJAX 操作都将由用户或应用程序的任何副作用触发,在那里您可以控制环境,对我来说,这是您应该将令牌、凭据等保存在 cookie、localStorage 等中。

    在不同的情况下混合使用两个令牌我认为这不是一个好的选择,因为它本身的行为(在构建项目时触发而不是由客户端触发)。

    因此,在回答您的问题时,您应该复制该部分代码(将其隔离到一个单独的函数中,并在需要时调用它两次)。

    【讨论】:

      猜你喜欢
      • 2020-06-23
      • 2021-05-08
      • 2021-01-17
      • 2020-08-11
      • 2018-07-23
      • 2021-09-09
      • 2019-04-02
      • 2018-03-15
      • 1970-01-01
      相关资源
      最近更新 更多