在 AWS Amplify 应用程序中,可以使用 IAM 凭证来调用受保护的 AWS 服务,比如 S3 和 DynamoDB。以下是如何假定 IAM 凭证的步骤:
首先,需要在 AWS Management Console 中创建一个 IAM 用户,并为其分配适当的权限。例如,可以将用户添加到一个具有访问 S3 存储桶和 DynamoDB 表的自定义策略中。
然后,在 AWS Amplify 配置文件中,需要添加以下内容:
{
"awscloudformation": {
"authenticationType": "AWS_IAM",
"credentialsProvider": "AWSCognitoCredentials",
"region": "YOUR_AWS_REGION"
}
}
在这里,authenticationType
设置为 AWS_IAM
,表示将使用 IAM 凭证进行身份验证。credentialsProvider
设置为 AWSCognitoCredentials
,表示使用 Amazon Cognito 进行身份验证。region
是 AWS 区域的名称,比如 us-east-1
。
Auth
类来获取 IAM 凭证:import Amplify, { Auth } from 'aws-amplify';
Amplify.configure({
Auth: {
identityPoolId: 'YOUR_IDENTITY_POOL_ID',
region: 'YOUR_AWS_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_APP_CLIENT_ID'
}
});
async function getData() {
const currentUser = await Auth.currentCredentials();
console.log(currentUser);
// Use currentUser to access protected resources
}
在这里,Auth
类的 currentCredentials()
方法用于获取当前用户的 IAM 凭证。可以使用这些凭证来调用受保护的 AWS 服务。
如果 IAM 用户的权限需要更新或撤销,可以通过 AWS Management Console 中的 IAM 控制台进行管理。