我正在开发一个使用 Amplify 和 Angular 的项目。我使用 Amplify 创建了一个 API,其中某些表可以由未经身份验证的用户访问 (
{allow: public, provider: iam, operations: [read]}
),有些需要登录。
在我的组件中使用生成的 APIService 时遇到此错误,如下所示
const response = await this.apiService.ListTodos()
:
Error: Uncaught (in promise): No current user
在没有登录用户的情况下如何使用 IAM 进行此调用?
谢谢!
更新授权
amplify update auth
--> 启用未经身份验证的用户
更新授权模式 -> IAM
amplify update api
更新您的 Amplify.configure
Amplify.configure({...awsExports,
DataStore: {
authModeStrategyType: AuthModeStrategyType.MULTI_AUTH
}});
更新 amplify 文件夹中 api 的架构
type Todo @model @auth(rules: [{allow: public, provider: iam, operations: [read] }]) { /** Model **/
上述授权仅允许未经身份验证的用户访问,为了允许经过身份验证的用户访问,我添加了类似的规则
{allow: private, provider: iam or userPool, operations: [read, create, update]
更新后台
amplify push
从 graphql 查询引用您的 api
import { API } from '@aws-amplify/api
import { listTodos } from './graphql/queries
let result = await API.graphql({ query: listTodos, authMode: 'AWS_IAM'});
检查身份验证
let user = await Auth.currentUserSession()
if(!user){
return false;
}
return true;
如果您使用 userPool 而不是查询未经身份验证的用户:
let result = await API.graphql({ query: listTodos, authMode: 'AWS_IAM'});
将是:
let result = null
if(!user) {
result = await API.graphql({ query: listTodos, authMode: 'AWS_IAM'});
}
result = await API.graphql({ query: listTodos});