使用 Cognito 用户池向 AWS AppSync 验证 Apollo 客户端

Exi*_*lis 5 javascript amazon-web-services apollo graphql aws-appsync

我正在尝试使用普通的 Apollo Client 连接到我的 AWS AppSync API,但我不确定如何正确构建身份验证标头。

到目前为止,我已经按照此处的标头身份验证文档进行操作:https : //www.apollographql.com/docs/react/recipes/authentication.html

并有此代码,我将其修改为包含对 Amplify 身份验证服务的令牌调用,但它返回 401 错误:

const httpLink = createHttpLink({
  uri: '[API end point address]/graphql'
});

const authLink = setContext((_, { headers }) => {
  const token = async () => (await Auth.currentSession()).getAccessToken().getJwtToken();
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  }
})

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})
Run Code Online (Sandbox Code Playgroud)

我能找到的与此相关的唯一文档没有提供任何技术说明:

使用 Amazon Cognito 用户池时,您可以创建用户所属的组。此信息编码在 JWT 令牌中,您的应用程序在发送 GraphQL 操作时将其在授权标头中发送到 AWS AppSync。

从这里:https : //docs.aws.amazon.com/appsync/latest/devguide/security.html

我知道令牌很好,因为如果我使用 AppSync JavaScript API 那么它就可以工作。有没有我可以去了解如何实现这一目标的地方,或者有人知道如何实现?

编辑:

到目前为止,我已尝试更改此行:

  authorization: token ? `Bearer ${token}` : ""
Run Code Online (Sandbox Code Playgroud)

以下尝试:

token

jwtToken: token

authorization: token

Authorization: token
Run Code Online (Sandbox Code Playgroud)

这些都没有奏效。

Jcl*_*gst 5

免责声明:从未尝试过,但这是我会做的:

在此处查看 AppSync 客户端代码作为为 Apollo 客户端和 AppSync 服务器创建身份验证链接的基础。看起来该代码为每种可用的身份验证方法提供了脚手架。

具体来说,如果您尝试使用 OPENID_CONNECT 身份验证方法,则 JWT 令牌似乎不需要预先添加Bearer(第 156 行)。