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

AWS SAM+Cognito+API Gateway:Curl令牌403但Postman令牌可用问题

问题描述

我部署了Cognito用户池(CognitoUserPool)和需要认证用户访问的Lambda函数。通过Postman使用AWS UI登录获取的令牌调用API可以正常访问,但用Curl登录获取的令牌调用时出现403 Forbidden错误,请问可能遗漏了什么配置?

我的template.yaml配置

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  Env:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - test
      - prod

Description: >-
  sam-app
Transform:
- AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 100
    Runtime: nodejs16.x
    MemorySize: 128

Resources:
  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Sub ${Env}-Cognito-User-Pool
      Policies:
        PasswordPolicy: 
          MinimumLength: 8
      UsernameAttributes:
        - email
      AutoVerifiedAttributes:
        - email
      Schema:
        - AttributeDataType: String
          Name: email
          Required: false

  CognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref CognitoUserPool
      ClientName: !Sub ${Env}-CognitoUserPoolClient
      GenerateSecret: false
      CallbackURLs:
        - http://localhost:3000
      LogoutURLs:
        - http://localhost:3000
      AllowedOAuthFlowsUserPoolClient: true
      ExplicitAuthFlows:
        - ALLOW_ADMIN_USER_PASSWORD_AUTH
        - ALLOW_USER_PASSWORD_AUTH
        - ALLOW_CUSTOM_AUTH
        - ALLOW_USER_SRP_AUTH
        - ALLOW_REFRESH_TOKEN_AUTH
        - ALLOW_USER_PASSWORD_AUTH
      AllowedOAuthFlows:
        - code
        - implicit
      SupportedIdentityProviders:
        - COGNITO
      AllowedOAuthScopes:
        - openid
        - email
        - profile

  CognitoDomainName:
    Type: AWS::Cognito::UserPoolDomain
    Properties:
      Domain: !Sub ${Env}-domain-test
      UserPoolId: !Ref CognitoUserPool

  HttpApi:
    Type: AWS::Serverless::HttpApi
    DependsOn: CognitoUserPoolClient
    Properties:
      StageName: !Ref Env
      Auth:
        Authorizers:
          CustomCognitoAuthorizer:
            UserPoolArn: !GetAtt CognitoUserPool.Arn
            AuthorizationScopes:
              - email
            IdentitySource: "$request.header.Authorization"
            JwtConfiguration:
              issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${CognitoUserPool}
              audience:
                - !Ref CognitoUserPoolClient
      CorsConfiguration:
        AllowMethods:
          - GET
        AllowHeaders: '*'
        AllowOrigins:
          - '*'

  getAllItemsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/get-all-items.getAllItemsHandler
      Events:
        DosGet:
          Type: HttpApi
          Properties:
            Auth:
              Authorizer: CustomCognitoAuthorizer
            Path: /
            ApiId: !Ref HttpApi
            Method: GET

使用的Curl登录命令

POST https://cognito-idp.{REGION}.amazonaws.com/
Content-Type: application/x-amz-json-1.1
X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth

Body:
{
    "AuthParameters" : {
        "USERNAME" : "YOUR_USERNAME",
        "PASSWORD" : "YOUR_PASSWORD"
    },
    "AuthFlow" : "USER_PASSWORD_AUTH",
    "ClientId" : "APP_CLIENT_ID"
}
可能的原因及解决方法
  • 令牌缺少授权范围
    你的HttpApi授权器要求令牌包含email scope,但USER_PASSWORD_AUTH流默认不会返回带该scope的令牌。需要在Curl请求的AuthParameters中添加SCOPE参数,指定所需权限:

    {
        "AuthParameters" : {
            "USERNAME" : "你的用户名",
            "PASSWORD" : "你的密码",
            "SCOPE": "email"
        },
        "AuthFlow" : "USER_PASSWORD_AUTH",
        "ClientId" : "你的客户端ID"
    }
    

    你的用户池客户端已配置AllowedOAuthScopes: ["email"],这部分无需修改。

  • 使用了错误的令牌类型
    Postman通过UI登录获取的是ID Token,而InitiateAuth返回结果里包含IdToken、AccessToken和RefreshToken三种令牌。API授权器验证的是JWT,需确保请求API时使用的是IdToken,用错令牌类型会直接导致403。

  • 用户状态未确认
    检查通过Curl登录的用户是否完成邮箱验证,用户池配置了自动验证邮箱,但如果是手动创建的用户可能未确认。在Cognito控制台查看用户状态,必须是CONFIRMED状态才能生成有效令牌。

  • AuthFlow参数匹配问题
    确认Curl请求中的AuthFlow值为USER_PASSWORD_AUTH,与用户池客户端配置的ALLOW_USER_PASSWORD_AUTH完全匹配,大小写不能出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:00:51