Cognito访问令牌签名验证失败,boto3调用GetUser报错求助
Cognito GetUser 调用提示“Could not verify signature for Access Token”问题解决
问题描述
我通过Flutter Amplify获取已登录用户的Access Token:
Future<void> fetchCognitoAuthSession() async { try { final cognitoPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey); final result = await cognitoPlugin.fetchAuthSession(); final userPoolTokensResult = result.userPoolTokensResult.toJson(); safePrint("Current user's userPoolTokensResult: $userPoolTokensResult"); } on AuthException catch (e) { safePrint('Error retrieving auth session: ${e.message}'); } }
但使用boto3调用Cognito的get_user接口时,收到未授权异常:
import boto3 client = boto3.client('cognito-idp') response = client.get_user( AccessToken='accesstoken') print(response)
错误信息:
botocore.errorfactory.NotAuthorizedException: An error occurred (NotAuthorizedException) when calling the GetUser operation: Could not verify signature for Access Token
同时在jwt.io上验证该令牌,提示未签名,不知道如何处理。
问题原因及解决步骤
1. 修复Access Token的签名配置
如果jwt.io显示令牌未签名,核心原因是你的Cognito用户池应用客户端的AccessToken签名算法设置为了NONE,导致生成的令牌无签名,Cognito无法完成验证。
解决操作:
- 登录AWS控制台,进入目标Cognito用户池
- 切换到「应用集成」标签,找到对应的应用客户端
- 点击「编辑」,在「令牌配置」区域,将「AccessToken」的签名算法修改为
RS256(官方推荐)或其他签名算法 - 保存配置后,重新生成AccessToken再尝试调用
2. 修正boto3调用逻辑
使用用户的AccessToken调用get_user属于用户自主身份验证操作,不需要AWS IAM凭证的请求签名,但boto3默认会自动添加AWS签名,导致Cognito验证逻辑冲突。
解决方法:创建不进行签名的boto3客户端
import boto3 from botocore.config import Config client = boto3.client( 'cognito-idp', region_name='你的用户池所属区域', config=Config(signature_version='UNSIGNED') ) response = client.get_user(AccessToken='你的有效AccessToken') print(response)
或者直接用requests库发送无签名请求,避免boto3的签名干扰:
import requests url = "https://cognito-idp.你的区域.amazonaws.com/" headers = { "Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": "AWSCognitoIdentityProviderService.GetUser" } data = { "AccessToken": "你的有效AccessToken" } response = requests.post(url, json=data, headers=headers) print(response.json())
3. 确认AccessToken的有效性
确保传递给get_user的是正确的AccessToken(而非ID Token或Refresh Token),且令牌未过期。可通过解析JWT的exp字段确认过期时间。
内容的提问来源于stack exchange,提问作者emmanuel_kb
相关产品推荐
相关产品推荐

