我正在使用 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 配置中。此外,如何获取未经身份验证的用户的凭据?
最佳答案
我建议在您的应用程序中使用 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 提供者: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-app
关于amazon-web-services - 具有 Cognito 联合身份的 AWS AppSync IAM 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48875610/