Reputation: 11
In Amplify V5 library, I was able to provide guest access to a GraphQL/App Sync api that I used in a registration user flow. To call the Appsync API as a guest, I would authenticate to using Cognito Identity pools and IAM auth.
This is how I would configure Amplify v5:
import { Amplify } from 'aws-amplify';
const amplifyConfig = {
Auth: {
identityPoolId: 'identity-pool-id',
region: 'region',
},
API: {
graphql_headers: async () => {
return {}
}
},
aws_appsync_graphqlEndpoint: 'graphql-endpoint',
aws_appsync_region: 'region',
aws_appsync_authenticationType: 'AWS_IAM',
};
Amplify.configure(amplifyConfig);
This is how I would sign in as guest, using AWS Cognito to authenticate as a guest. This was achieved by calling Auth.currentCredentials():
import { Auth } from '@aws-amplify';
export async function signInAsGuest() {
try {
await Auth.currentCredentials();
} catch (error) {
console.error('Error signing in as a guest:', error);
}
}
An this is how you would make the GraphQL call signed in to the identity pool, using IAM auth:
import { API, Auth } from '@aws-amplify';
import { signInAsGuest } from './auth/guest'
import { createUser } from './graphql/queries';
async function registerUser() {
try {
signInAsGuest();
const response = await API.graphql(graphqlOperation(createUser));
Auth.signOut();
} catch (error) {
console.error('Error:', error);
}
}
This used to work fine. Now in v6, Auth.currentCredentials is deprecated. It suggests to use fetchAuthSession
API. When I do, the result is an empty session object, and when I call the GraphQL API it returns:
Error: No credentials
This is the v6 code Im using to configure Amplify:
export const appsyncGuestResourcesConfig = {
Auth: {
Cognito: {
identityPoolId: 'identity-pool-id'
}
},
API: {
GraphQL: {
endpoint: 'graphql-endpoint',
defaultAuthMode: 'iam'
}
}
}
export const appsyncGuestLibraryOptions = {
API: {
GraphQL: {
headers: async () => {
return {}
}
}
}
}
Amplify.configure(appsyncGuestResourcesConfig, appsyncGuestLibraryOptions)
This is how I'm trying to sign in as guest:
import { fetchAuthSession } from '@aws-amplify/auth';
export async function signInAsGuest() {
try {
await fetchAuthSession();
} catch (error) {
console.error('Error signing in as a guest:', error);
}
}
As mentioned above, the result is an empty session object, and when I call the GraphQL API it returns:
Error: No credentials.
I would appreciate help on how to achieve the above using v6 of Amplify.
Upvotes: 0
Views: 239
Reputation: 11
The answer is to add allowGuestAccess: true
. This now allows the user who is guest to call to appsync.
export const appsyncGuestResourcesConfig = {
Auth: {
Cognito: {
identityPoolId: 'identity-pool-id',
allowGuestAccess: true
}
},
API: {
GraphQL: {
endpoint: 'graphql-endpoint',
defaultAuthMode: 'iam'
}
}
}
export const appsyncGuestLibraryOptions = {
API: {
GraphQL: {
headers: async () => {
return {}
}
}
}
}
Amplify.configure(appsyncGuestResourcesConfig, appsyncGuestLibraryOptions)
Upvotes: 0