AWS Amplify- Use un-authenticate user Cognito auth instead of ApiKey

AWS Amplify- Use un-authenticate user Cognito auth instead of ApiKey

When using ApiKey to access AppSync (GraphQL), there is a problem with rotating apiKey.

There is no default way to rotate apiKey in AWS-amplify. We have to rotate apiKey manually(default is 7 days, can be up to 365 days)

Instead, using an Unauthenticated user can solve this problem of manually updating.

Below is the configuration:

Change schema.graphql definition file:

type Post
  @model
  @auth(
    rules: [
      # allow all guest users (not authenticated) to read,create
      { allow: public,provider: iam, operations: [create, read] }
    ]
  ) {
  id: ID!
  ...
  }

add authMode: 'AWS_IAM' parameter  to API call usages like the below:

const response = await API.graphql({
        query: getPost,
        variables: {
          id: postId
        },
        authMode: 'AWS_IAM'
      })

Add auth:

$ amplify add auth
? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings?  No, I am done.

$amplify push

Allow Allow unauthenticated logins

make sure you choose: YES for  Allow unauthenticated logins?  question

$ amplify update auth
What do you want to do? Walkthrough all the auth configurations
 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM controls
 (Enables per-user Storage features for images or other content, Analytics, and more)
 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
 Do you want to enable 3rd party authentication providers in your identity pool? No
 Do you want to add User Pool Groups? No
 Do you want to add an admin queries API? No
 Multifactor authentication (MFA) user login options: OFF
 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
 Specify an email verification subject: Your verification code
 Specify an email verification message: Your verification code is {####}
 Do you want to override the default password policy for this User Pool? No
 Specify the app's refresh token expiration period (in days): 30
 Do you want to specify the user attributes this app can read and write? No
 Do you want to enable any of the following capabilities? 
 Do you want to use an OAuth flow? No
? Do you want to configure Lambda Triggers for Cognito? No

$ amplify push

Import Auth to the project:

import { Amplify,  Auth  } from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
Auth.configure(awsExports);
....

Done