AWS Amplify Auth.currentAuthenticatedUser()无法拉取Cognito用户池自定义属性
解决方案:AWS Amplify无法获取Cognito自定义属性
常见原因及解决步骤
1. 检查Cognito App Client的属性读取权限
这是最常见的问题根源:你的App Client未被授权读取自定义属性custom:group。
- 登录AWS控制台,进入目标Cognito用户池
- 切换到App integration -> App clients and analytics,找到你的应用客户端
- 点击Edit,滚动到Attribute read and write permissions区域
- 在Readable attributes列表中勾选
custom:group,保存配置
2. 强制绕过缓存拉取最新用户数据
Amplify默认会缓存用户数据,可能导致你拿到的是旧的、不包含自定义属性的缓存数据。修改checkUser函数,添加bypassCache: true参数:
async function checkUser() { try { // 强制从服务器获取最新用户数据,跳过本地缓存 const user = await Auth.currentAuthenticatedUser({ bypassCache: true }); const userGroup = user.attributes["custom:group"]; console.log("USER GROUP", userGroup) } catch (error) { console.log(error); } }
3. 验证JWT令牌是否包含自定义属性
如果上述步骤无效,需要确认Cognito颁发的令牌中是否包含custom:group:
- 打开浏览器开发者工具的Application标签
- 在Local Storage中找到以
CognitoIdentityServiceProvider.<你的ClientId>为前缀的存储项,取出idToken - 解码令牌的Payload部分(可在浏览器控制台执行
atob(idToken.split('.')[1])查看) - 如果Payload中没有
custom:group字段,需要:- 回到Cognito用户池的App client settings,确保Allowed OAuth scopes包含
profile(自定义属性默认归属该Scope) - 确认用户池的自定义属性
custom:group已正确配置,且用户属性值确实存在
- 回到Cognito用户池的App client settings,确保Allowed OAuth scopes包含
4. 重新认证用户
修改Cognito配置后,旧的令牌不会自动更新。让用户登出当前会话,再重新登录,获取包含最新属性的新令牌。
注意事项
- 自定义属性的键名区分大小写,确保代码中
user.attributes["custom:group"]的拼写和Cognito中配置的完全一致 - 若使用Amplify CLI管理配置,确保
aws-exports.js中的oauth配置包含了正确的Scope
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

