5

我正在使用 AWS AppSync,并使用 Cognito 联合身份登录用户。

我希望未经身份验证的用户可以访问某些端点,而经过身份验证的用户将可以访问其他端点。

我已经为上述每个配置了 IAM 角色,例如 "Resource": [ "Region:Account:apis/AppSyncName/types/Mutation/fields/XXX”]

我的问题是 — 我如何使用 Cognito 联合身份获取凭据以通过 AppSync 客户端发送。

我对 AppSync 的配置:

const client = new AWSAppSyncClient({
  url: config.AppSync.ENDPOINT,
  region: config.AppSync.REGION,
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: () => ReturnCredentials()
  }
});

我的登录功能

login(username, password) {
    const user = new CognitoUser({ Username: username, Pool: userPool });
    const authenticationData = { Username: username, Password: password };
    const authenticationDetails = new AuthenticationDetails(authenticationData);
    var responseFunctions = {
      onSuccess: result => {
      },
      onFailure: err => {
        console.log(err);
      }
    };

    user.authenticateUser(authenticationDetails, responseFunctions);
  }

我想我需要在登录后使用GetCredentialsForIdentity,但不确定如何将这些传递到 AppSync 配置中。此外,如何获取未经身份验证的用户的凭据?

4

1 回答 1

5

我建议在您的应用程序中使用 AWS Amplify:https ://github.com/aws/aws-amplify

npm install aws-amplify --save

然后,您将能够Auth在 AppSync 客户端构造函数中使用 Amplify 中的模块,如下所示:

const client = new AWSAppSyncClient({
    url: AppSync.graphqlEndpoint,
    region: AppSync.region,
    auth: {
        credentials: () => Auth.currentCredentials(),
    },
});

从那里您将client对象传递给 Apollo GraphQL Provider:

const WithProvider = () => (
    <ApolloProvider client={client}>
        <Rehydrated>
            <App />
        </Rehydrated>
    </ApolloProvider>
);

现在,您可以开始使用 Apollo 对 AWS AppSync 进行标准 GraphQL 调用。数据将自动离线保存,但如果您想进行离线突变,您需要配置 Optimistic UI。您可以在此处阅读所有这些内容:https ://docs.aws.amazon.com/appsync/latest/devguide/building-a-client-app-react.html#import-the-appsync-sdk-into-your-应用程序

于 2018-02-21T00:47:47.313 回答