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

Authenticate Apollo Client to AWS AppSync with Cognito User Pools

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

到目前为止,我已经遵循了此处的 header 身份验证文档:https://www.apollographql.com/docs/react/recipes/authentication.html

并拥有此代码,我对其进行了调整以包括对 Amplify 身份验证服务的令牌调用,但它 returns 出现 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()
})

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

When using Amazon Cognito User Pools, you can create groups that users belong to. This information is encoded in a JWT token that your application sends to AWS AppSync in an authorization header when sending GraphQL operations.

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

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

编辑:

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

  authorization: token ? `Bearer ${token}` : ""

以下尝试:

token

jwtToken: token

authorization: token

Authorization: token

None 这些都有效。

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

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

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

您可以在 Github 上从 AWS 示例中看到它的示例。 与 AppSync 一起工作,但非常相似。

// AppSync client instantiation
const client = new AWSAppSyncClient({
  url: GRAPHQL_API_ENDPOINT_URL,
  region: GRAPHQL_API_REGION,
  auth: {
    type: AUTH_TYPE,
    // Get the currently logged in users credential.
    jwtToken: async () => (await Auth.currentSession()).getAccessToken().getJwtToken(),
  },
  // Amplify uses Amazon IAM to authorize calls to Amazon S3. This provides the relevant IAM credentials.
  complexObjectsCredentials: () => Auth.currentCredentials()
});

Link 到 AWS repo