React Native中Auth.currentAuthenticatedUser()与Auth.currentSession()无返回值问题
React Native + Amplify Cognito:自动认证检查无返回值的排查方案
1. 修复配置语法错误
你的amplifySetup函数中identityPoolRegion的值存在引号未闭合的语法错误,这会导致Amplify配置失效,先修正:
async function amplifySetup() { Amplify.configure({ Auth: { identityPoolId: 'REGION:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', region: "REGION", identityPoolRegion: "REGION", // 补上闭合引号 userPoolId: "REGION_XXXXXXXX", userPoolWebClientId: "XXXXXXXXXXXXXXXXXXXXXX", }, }); }
2. 确保配置完成后再调用Auth方法
amplifySetup是异步函数,直接调用不会等待配置完成就执行后续代码。需在useEffect中等待配置完成后再检查认证状态:
import { Auth } from 'aws-amplify'; import amplifySetup from './amplifySetup'; import { useState, useEffect } from 'react'; function App() { const [loading, setLoading] = useState(true); const [isAuthenticated, setIsAuthenticated] = useState(false); useEffect(() => { const checkAuthStatus = async () => { try { // 等待Amplify配置完成 await amplifySetup(); // 尝试获取当前认证用户,可设置bypassCache=true强制从服务端拉取 const user = await Auth.currentAuthenticatedUser({ bypassCache: false }); setIsAuthenticated(true); console.log('当前用户:', user); } catch (error) { // 未认证或会话异常时捕获错误,打印信息定位问题 console.error('认证检查失败:', error); setIsAuthenticated(false); } finally { setLoading(false); } }; checkAuthStatus(); }, []); if (loading) { return <Text>加载中...</Text>; } // 后续渲染逻辑 return ( // ... ); }
3. 捕获错误信息(关键)
Auth.currentAuthenticatedUser()和Auth.currentSession()在未认证或会话异常时会抛出错误,而非返回null。常见错误类型:
NotAuthorizedException:令牌过期或无效No current user:本地存储中无会话数据UserNotFoundException:用户不存在(登录过的话可能性极低)
4. 检查本地存储的会话数据
登录成功后,Amplify会将会话信息存在本地存储(React Native默认用AsyncStorage或MMKV)。可在登录成功后检查存储内容,确认会话是否被正确保存:
import AsyncStorage from '@react-native-async-storage/async-storage'; // 登录成功后执行 const checkStorage = async () => { const allKeys = await AsyncStorage.getAllKeys(); const cognitoKeys = allKeys.filter(key => key.includes('CognitoIdentityServiceProvider')); console.log('Cognito存储键:', cognitoKeys); if (cognitoKeys.length > 0) { const sessionData = await AsyncStorage.getItem(cognitoKeys[0]); console.log('会话数据:', sessionData); } };
如果登录后无Cognito相关存储键,说明Amplify未正确保存会话,需检查版本或存储配置。
5. 检查Amplify版本与依赖
- 若使用Amplify v6,需单独安装
@aws-amplify/auth并导入:import { Auth } from '@aws-amplify/auth'; - 避免混用不同大版本的Amplify包(如
aws-amplifyv5和@aws-amplify/authv6) - 确保
@react-native-async-storage/async-storage(或MMKV)版本与Amplify兼容
6. 检查Cognito用户池客户端配置
- 确认用户池客户端的认证流程包含
USER_PASSWORD_AUTH(适配Auth.signIn()的使用场景) - 检查会话过期时间:若
Access Token过期过短,重启应用时令牌可能已失效 - 避免启用未配置的
Enhanced authentication(如MFA)
7. 平台特定配置检查
iOS
在Info.plist中添加Keychain访问权限:
<key>NSFaceIDUsageDescription</key> <string>需要访问Keychain存储用户认证信息</string>
Android
确保AndroidManifest.xml包含互联网权限:
<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者0xFarted
相关产品推荐
相关产品推荐

