如何在AWS Amplify Gen2中同时启用userPool与identityPool两种认证模式
如何在AWS Amplify Gen2中同时启用userPool与identityPool两种认证模式
嘿,我来帮你搞定这个问题!你想实现的「未认证用户只读、认证用户全权限」的需求,其实你的Schema已经写对了核心规则,只是在Amplify数据资源的配置上漏了开启Identity Pool的支持,导致两种认证模式没法同时工作。
具体要做的修改其实很简单,分两步走:
1. 启用Identity Pool认证模式
在你导出data的defineData配置中,需要补充Identity Pool的相关设置,告诉Amplify你要同时支持两种认证模式,并且允许未认证用户访问。把原来的authorizationModes部分替换成下面的配置:
authorizationModes: { defaultAuthorizationMode: 'userPool', // 认证用户默认用User Pool identityPoolAuthorizationMode: 'identityPool', // 启用Identity Pool作为备选模式 allowUnauthenticatedIdentities: true // 允许未认证用户(游客)访问 }
这样配置后,Amplify就会同时支持User Pool(处理登录用户的请求)和Identity Pool(处理未认证游客的请求)两种认证方式了。
2. 确认Schema中的授权规则(你已经做对了!)
看你写的Schema,Listing模型已经正确配置了双授权规则:
allow.authenticated():给登录用户(通过User Pool认证)开放全权限allow.guest().to(['read']):给未认证游客(通过Identity Pool)只开放只读权限RentOrder模型只允许认证用户访问,这个设置也完全没问题。
完整的修改后代码
这里把所有代码整合好,你可以直接复制使用:
import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; const schema = a.schema({ Listing: a.model({ title: a.string(), description: a.string(), imageUrl: a.string(), price: a.float(), sellerId: a.string(), category: a.string(), location: a.string(), createdAt: a.datetime(), }).authorization((allow) => [ allow.authenticated(), allow.guest().to(['read']), ]), RentOrder: a.model({ advId: a.string(), borrowerUserId: a.string(), lenderUserID: a.string(), borrowerEmailID: a.string(), lenderEmailID: a.string(), rentValue: a.string(), commonID: a.string(), }).authorization((allow) => [allow.authenticated()]) }); export type Schema = ClientSchema<typeof schema>; export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'userPool', identityPoolAuthorizationMode: 'identityPool', allowUnauthenticatedIdentities: true }, });
为什么这样就生效了?
之前你的配置只指定了默认用User Pool,但没有启用Identity Pool的支持,Amplify没法识别allow.guest()规则对应的认证方式。现在补上identityPoolAuthorizationMode和allowUnauthenticatedIdentities后,系统就知道:
- 登录用户的请求用User Pool认证,走
allow.authenticated()的规则 - 未认证的游客请求用Identity Pool认证,走
allow.guest()的只读规则
这样就完美实现了你想要的权限划分啦!
内容来源于stack exchange
相关产品推荐
相关产品推荐

