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
ProviderARNscorrectly references your User Pool ARN viaFn::GetAtt: [CognitoUserPool, Arn] IdentitySource: method.request.header.Authorizationmatches 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
- Create a new POST request in Postman to:
https://<your-cognito-domain>/oauth2/token - Set the request header:
Content-Type: application/x-www-form-urlencoded - Add these form data parameters:
grant_type:passwordclient_id: Your Cognito User Pool Client ID (from Serverless outputs or AWS Console)username: Your test user's email/usernamepassword: Your test user's password
- Send the request—you'll get a response with
id_token,access_token, andrefresh_token. Copy theid_token.
Step 2: Test the API Gateway Endpoint
- Create a GET request to your API Gateway endpoint (e.g.,
https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/your-path) - Add the request header:
Authorization: Bearer <your-copied-id-token>(note: theBearerprefix is optional but recommended for consistency) - 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

