如何在Android Amplify中用Cognito身份池实现未认证用户获取AWS凭证
解决Android Amplify+Cognito未认证用户获取凭证的问题
我明白你的困扰——明明已经在Cognito里开了未认证用户支持,但调用fetchAuthSession还是提示已登出,而且找不到专门针对未认证用户的API。其实问题出在Amplify默认不会自动为未认证用户创建身份会话,你需要显式触发这个流程。
关键步骤:
确认Amplify配置正确
先检查你的amplifyconfiguration.json文件,确保Auth模块的allowGuestAccess设置为true,比如:"auth": { "plugins": { "awsCognitoAuthPlugin": { "UserAgent": "aws-amplify-cli/2.0", "Version": "1.0", "IdentityManager": { "Default": {} }, "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "你的身份池ID", "Region": "你的区域" } } }, "CognitoUserPool": { "Default": { "PoolId": "你的用户池ID", "AppClientId": "你的客户端ID", "Region": "你的区域" } }, "Auth": { "Default": { "authenticationFlowType": "USER_SRP_AUTH", "allowGuestAccess": true } } } } }显式初始化未认证会话
在调用fetchAuthSession之前,需要先调用Amplify.Auth.signInWithGuest()来为未认证用户创建身份。这个方法就是你要找的针对未认证用户的函数,它会自动向Cognito请求未认证身份并初始化会话。
完整代码示例:
// 先初始化未认证用户会话 Amplify.Auth.signInWithGuest( result -> { Log.i("AuthQuickStart", "未认证用户登录成功"); // 会话初始化后,再获取身份和凭证 fetchAuthSession(); }, error -> Log.e("AuthQuickStart", "未认证用户登录失败: " + error.toString()) ); // 封装的fetchAuthSession方法 private void fetchAuthSession() { Amplify.Auth.fetchAuthSession( result -> { AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result; switch (cognitoAuthSession.getIdentityId().getType()) { case SUCCESS: Log.i("AuthQuickStart", "IdentityId: " + cognitoAuthSession.getIdentityId().getValue()); // 这里还可以获取凭证 AWSCredentials credentials = cognitoAuthSession.getAwsCredentials().getValue(); Log.i("AuthQuickStart", "Access Key: " + credentials.getAWSAccessKeyId()); Log.i("AuthQuickStart", "Secret Key: " + credentials.getAWSSecretKey()); break; case FAILURE: Log.i("AuthQuickStart", "IdentityId获取失败: " + cognitoAuthSession.getIdentityId().getError().toString()); } }, error -> Log.e("AuthQuickStart", "获取会话失败: " + error.toString()) ); }
额外提示:
- 你可以在App启动时或者需要使用未认证用户权限的地方调用
signInWithGuest(),不需要每次都调用——Amplify会缓存未认证会话,除非会话过期或者用户登出。 - 如果想检查当前是否已有未认证会话,可以先调用
Amplify.Auth.getCurrentUser(),如果返回null或者用户是未认证状态,再执行signInWithGuest()。
内容的提问来源于stack exchange,提问作者Mercury
相关产品推荐
相关产品推荐

