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

React集成AWS Cognito与API Gateway遇CORS及授权问题求助

问题分析与分步解决方案

Let's break down your issues step by step and fix them one by one:


1. Fix the CORS Error First

The core mistake here is that you're sending server-side CORS response headers from your frontend request. Headers like Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers are meant to be returned by the API server, not sent in the client's request. Including them in your fetch call triggers the preflight error you're seeing.

Step 1: Clean up your frontend API code

Remove those invalid request headers and use the correct authentication token:

callAPI = async (url) => {
  // Get the user's Cognito User Pool session (not credentials)
  const session = await Amplify.Auth.currentSession();
  // Use ID Token for identity authentication (or Access Token for resource authorization)
  const authToken = session.getIdToken().getJwtToken();

  const apiurl = 'https...?url=' + url
  const response = await fetch(apiurl, {
    method: 'GET',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json', // Only include if your API requires it
      Authorization: authToken // Correct token for Cognito User Pool authorizer
    },
  })
  const data = await response.json();
  // ... rest of your logic
}

Step 2: Update Serverless API Gateway CORS configuration

The default cors: true setting isn't enough—you need to explicitly allow the Authorization header in your CORS rules:

events:
  - http:
      path: '{proxy+}'
      method: get
      cors:
        origin: 'http://localhost:3000' # Restrict to your frontend domain in production
        headers:
          - Content-Type
          - Authorization # Critical: allows the frontend to send this header
          - X-Requested-With
        allowCredentials: false # Set to true only if you need to send cookies
      integration: lambda
      authorizer:
        type: COGNITO_USER_POOLS
        authorizerId: Ref: ApiGatewayAuthorizer

Step 3: Add CORS headers to your Lambda response

Your Lambda function must return valid CORS headers in its response to complete the flow:

exports.handler = async (event) => {
  const response = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "http://localhost:3000", // Match API Gateway setting
      "Access-Control-Allow-Headers": "Content-Type,Authorization"
    },
    body: JSON.stringify({ data: "Your response data" }),
  };
  return response;
};

2. Use the Correct Authorization Token

You were using currentCredentials() which fetches Cognito Identity Pool credentials—this is for AWS service access, not API Gateway User Pool authentication. Instead:

  • Use Amplify.Auth.currentSession() to get the user's active User Pool session
  • Extract either:
    • ID Token: For identity verification (contains user profile data)
    • Access Token: For resource authorization (grants access to specific resources)
      Both work with your COGNITO_USER_POOLS authorizer, but ID Token is standard for authentication use cases.

3. Verify Your Serverless Authorizer Configuration

Your existing authorizer setup looks correct, but double-check these details:

  • The ProviderARNs correctly references your User Pool ARN via Fn::GetAtt: [CognitoUserPool, Arn]
  • IdentitySource: method.request.header.Authorization matches where you're sending the token
  • Ensure your API Gateway stage is redeployed after making configuration changes (Serverless usually handles this, but manual redeployment can fix caching issues)

4. Test with Postman

Follow these steps to validate your setup:

Step 1: Get a Cognito User Pool Token

  1. Create a new POST request in Postman to:
    https://<your-cognito-domain>/oauth2/token
  2. Set the request header: Content-Type: application/x-www-form-urlencoded
  3. Add these form data parameters:
    • grant_type: password
    • client_id: Your Cognito User Pool Client ID (from Serverless outputs or AWS Console)
    • username: Your test user's email/username
    • password: Your test user's password
  4. Send the request—you'll get a response with id_token, access_token, and refresh_token. Copy the id_token.

Step 2: Test the API Gateway Endpoint

  1. Create a GET request to your API Gateway endpoint (e.g., https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/your-path)
  2. Add the request header: Authorization: Bearer <your-copied-id-token> (note: the Bearer prefix is optional but recommended for consistency)
  3. Send the request:
    • A 200 response means your authentication and CORS are working
    • A 401 response means the token is invalid or the authorizer is misconfigured
    • A CORS error means your API Gateway/Lambda CORS headers are still incorrect

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:21:42