Reputation: 83
I am using AWS AppSync, and logging in users with Cognito Federated Identities.
I'm hoping to have unauthenticated users have access to certain endpoints, while authenticated users will have access to other endpoints.
I have configured IAM Roles for each of the aforementioned, using e.g. "Resource": [ "Region:Account:apis/AppSyncName/types/Mutation/fields/XXX”]
My question is — how can I, using Cognito Federated Identities, get credentials to send through the AppSync Client.
My configuration for AppSync:
const client = new AWSAppSyncClient({
url: config.AppSync.ENDPOINT,
region: config.AppSync.REGION,
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: () => ReturnCredentials()
}
});
My Login Function
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);
}
I think I need to use GetCredentialsForIdentity after logging in, but am unsure how to pass these into the AppSync config. Moreover, how can I get credentials for an Unauthenticated user?
Upvotes: 5
Views: 1869
Reputation: 1780
I would suggest using AWS Amplify in your application: https://github.com/aws/aws-amplify
npm install aws-amplify --save
You will then be able to use the Auth
module from Amplify inside the AppSync client constructor like so:
const client = new AWSAppSyncClient({
url: AppSync.graphqlEndpoint,
region: AppSync.region,
auth: {
credentials: () => Auth.currentCredentials(),
},
});
From there you pass the client
object to the Apollo GraphQL Provider:
const WithProvider = () => (
<ApolloProvider client={client}>
<Rehydrated>
<App />
</Rehydrated>
</ApolloProvider>
);
Now you can start making standard GraphQL calls to AWS AppSync using Apollo. The data will automatically be persisted offline but if you'd like to do offline mutations you'll need to configure Optimistic UI. You can read about all this here: https://docs.aws.amazon.com/appsync/latest/devguide/building-a-client-app-react.html#import-the-appsync-sdk-into-your-app
Upvotes: 5