使用Cognito联合身份进行AWS AppSync IAM授权

nic*_*ick 5 amazon-web-services amazon-cognito aws-appsync

我正在使用AWS AppSync,并使用Cognito Federated Identities登录用户.

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

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

我的问题是 - 我如何使用Cognito Federated Identities获取通过AppSync客户端发送的凭据.

我对AppSync的配置:

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

我的登录功能

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);
  }
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*ard 5

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

npm install aws-amplify --save
Run Code Online (Sandbox Code Playgroud)

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

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

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

const WithProvider = () => (
    <ApolloProvider client={client}>
        <Rehydrated>
            <App />
        </Rehydrated>
    </ApolloProvider>
);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用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-应用