在 Amplify V5 库中,我能够提供对我在注册用户流程中使用的 GraphQL/App Sync API 的访客访问。要以访客身份调用 Appsync API,我将使用 Cognito 身份池和 IAM 身份验证进行身份验证。
这就是我配置 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);
这就是我以访客身份登录的方式,使用 AWS Cognito 以访客身份进行身份验证。这是通过调用 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);
}
}
这是使用 IAM 身份验证使 GraphQL 调用登录到身份池的方法:
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);
}
}
这曾经工作得很好。现在在 v6 中,Auth.currentCredentials 已已弃用。建议使用
fetchAuthSession
API。当我这样做时,结果是一个空的会话对象,当我调用 GraphQL API 时,它返回:
Error: No credentials
这是我用来配置 Amplify 的 v6 代码:
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)
这就是我尝试以访客身份登录的方式:
import { fetchAuthSession } from '@aws-amplify/auth';
export async function signInAsGuest() {
try {
await fetchAuthSession();
} catch (error) {
console.error('Error signing in as a guest:', error);
}
}
如上所述,结果是一个空的会话对象,当我调用 GraphQL API 时,它返回:
Error: No credentials.
我希望获得有关如何使用 Amplify v6 实现上述目标的帮助。
答案是添加
allowGuestAccess: true
。现在,访客用户可以调用 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)