Search code examples
amazon-web-servicesamazon-cognitoaws-amplifyaws-appsync

not understanding AWS Amplify authentication flow


I am trying to create a custom AWS Amplify authentication flow with code similar to the following taken from amazon's website:

import { Auth } from 'aws-amplify';

async function signUp() {
    try {
        const user = await Auth.signUp({
            username,
            password,
            attributes: {
                email,          // optional
                phone_number,   // optional - E.164 number convention
                // other custom attributes 
            }
        });
        console.log({ user });
    } catch (error) {
        console.log('error signing up:', error);
    }
}

I have a few questions about this.

  1. How are the tokens refreshed? If I am saving the credentials in the user variable, is this automatically refreshed somehow behind the scenes?

  2. How do I make authenticated graphql requests after I add a graphql api? With the pre-baked authentication flow it keeps track of who you are automatically. How do I do this when I log in this way?

Thanks!


Solution

    1. Yes, they are refreshed when necessary, except if you are using a different social provider. You can find more information on their documentation here, here and here

    By default, Amplify will automatically refresh the tokens for Google and Facebook, so that your AWS credentials will be valid at all times.

    ...

    you do not need to refresh Amazon Cognito tokens manually. The tokens are automatically refreshed by the SDK when necessary.

    ...

    use Auth.signUp and Auth.signIn (or an Amplify UI component) to complete this process and retrieve tokens. The Amplify client will refresh the tokens calling Auth.currentSession if they are no longer valid.

    1. When you instantiate your AppSync client you define how it is going to retrieve the token i.e:
        const client = new AWSAppSyncClient({
            url: config.aws_appsync_graphqlEndpoint,
            region: config.aws_appsync_region,
            auth: {
              type: config.aws_appsync_authenticationType,
              apiKey: config.aws_appsync_apiKey,
              jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
            },
        });