You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI-CloudAuth集成AWS Cognito遇JWK公钥未找到401错误求助

问题:FastAPI-CloudAuth 集成AWS Cognito返回401错误:"JWK public Attribute for authorization token not found"

调用接口时返回401错误,错误详情如下:

{
    "detail": "JWK public Attribute for authorization token not found"
}

使用的curl调用命令:

curl --location 'http://127.0.0.1:5000/access' \
--header 'Authorization: Bearer XXX'

实现代码(基本遵循官方示例):

import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from fastapi_cloudauth.cognito import Cognito, CognitoCurrentUser, CognitoClaims

app = FastAPI()
auth = Cognito(
    region="eu-xxxx",
    userPoolId="eu-north-xxxx",
    client_id="xxxx"
)

@app.get("/", dependencies=[Depends(auth.scope(["read:users"]))])
def secure():
    # access token is valid
    return "Hello"


class AccessUser(BaseModel):
    sub: str


@app.get("/access/")
def secure_access(current_user: AccessUser = Depends(auth.claim(AccessUser))):
    # access token is valid and getting user info from access token
    return f"Hello", {current_user.sub}


get_current_user = CognitoCurrentUser(
    region="eu-xxxx",
    userPoolId="eu-north-xxxx",
    client_id="xxxx"
)


@app.get("/user/")
def secure_user(current_user: CognitoClaims = Depends(get_current_user)):
    # ID token is valid and getting user info from ID token
    return f"Hello, {current_user.username}"

补充信息:

  • 未找到指定Cognito回调URL的配置位置
  • 该用户池在Flask等其他框架中可正常使用
  • 可手动访问cognito-idp地址,且确认令牌有效
  • 服务运行在本地localhost环境

解决办法

1. 确认令牌类型与验证逻辑匹配

Cognito类默认验证Access Token,CognitoCurrentUser默认验证ID Token,两类令牌的JWK公钥来源不同,混用会导致找不到对应密钥:

  • 调用/access/接口时,必须使用Access Token;调用/user/接口时,必须使用ID Token;
  • 若需强制指定验证的令牌类型,初始化时可添加token_type参数:
    # 强制验证ID Token
    auth = Cognito(
        region="eu-north-1",
        userPoolId="eu-north-xxxx",
        client_id="xxxx",
        token_type="id_token"
    )
    

2. 核对用户池参数准确性

检查代码中region、userPoolId、client_id是否与AWS控制台的实际配置完全一致:

  • region需填写完整的AWS区域代码(如eu-north-1,不要使用占位符);
  • userPoolId是用户池的完整ID,格式为区域_随机字符串;
  • client_id需与生成令牌时使用的应用客户端ID一致。

3. 确保JWK端点可访问

FastAPI-CloudAuth会自动从Cognito的JWK端点获取公钥验证签名,若本地服务无法访问该端点会导致报错:

  • 手动访问对应区域的JWK端点,确认能正常返回JWK数据;
  • 若存在网络限制,临时关闭防火墙或配置代理,让服务能正常访问该端点。

4. 关于回调URL的说明

回调URL仅用于OAuth2授权码流程获取令牌,与当前令牌验证报错无关。若后续要实现完整授权流程,可在AWS控制台的用户池「应用客户端」配置中添加回调URL(如http://localhost:5000/callback)。


内容的提问来源于stack exchange,提问作者NOOBAF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:42:49