Fix 401 unauthorized on API Gateway

Quick Answer: The "401 Unauthorized" error on API Gateway indicates that the request lacks valid authentication credentials for the target resource. The most likely cause is a missing or expired API key, an invalid JWT, or a misconfigured IAM role. First, verify the `Authorization` header in your request. Ensure it contains a valid API key, JWT, or AWS SigV4 signature. Expect a successful 200 OK response if credentials are correct and authorized.

What Causes This Error

Step-by-Step Fixes

Fix 1: Verify API Key Configuration and Usage

Navigate to the API Gateway console, select your API, then 'API Keys'. Confirm the API Key exists and is enabled.,Go to 'Usage Plans', select the relevant plan, and ensure the API Key is associated with it. Verify the plan is linked to the correct API stage.,Check your client-side request to ensure the `x-api-key` header is present and its value exactly matches the API Key from the console.,If using a usage plan, ensure the API Key is correctly mapped to the usage plan and that the method requires an API Key in its Integration Request settings.

Fix 2: Inspect JWT Token and Authorizer Settings

Decode your JWT using a tool like jwt.io. Verify its expiration (`exp`), issuer (`iss`), audience (`aud`), and other claims against your Cognito User Pool or custom authorizer's expectations.,In the API Gateway console, go to 'Authorizers'. Select your JWT authorizer and check its 'Token source' (e.g., `Authorization`).,If using a Cognito User Pool authorizer, confirm the 'Cognito User Pool' ARN is correct. If using a Lambda authorizer, verify the 'Lambda Function' ARN and ensure the Lambda function is returning a valid IAM policy.,Test the authorizer independently using the 'Test' button in the API Gateway console with a sample token to isolate authorizer issues.

Fix 3: Review IAM Permissions for AWS_IAM Authorizer

Identify the IAM role or user credentials used to sign the request. This is typically done via AWS Signature Version 4 (SigV4).,In the IAM console, review the attached policies for the identified role/user. Ensure it has `execute-api:Invoke` permission for the specific API Gateway resource (e.g., `arn:aws:execute-api:REGION:ACCOUNT_ID:API_ID/STAGE_NAME/METHOD/PATH`).,Verify that the `Action` and `Resource` elements in the IAM policy correctly match the API Gateway method being invoked.,If using STS assumed roles, ensure the trust policy allows the principal to assume the role and the assumed role has the necessary `execute-api:Invoke` permissions.

Fix 4: Debug Lambda Custom Authorizer Logic

Access CloudWatch Logs for your Lambda custom authorizer function. Look for recent invocation logs corresponding to the 401 errors.,Analyze the Lambda function's execution output. Ensure it's returning a valid IAM policy document (e.g., `Allow` for the resource) and not an explicit `Deny` or an error.,Add detailed logging within your Lambda authorizer to print the incoming token, decoded claims, and the generated policy to pinpoint where the authorization decision is being made.,Check for any environment variables or external dependencies within the Lambda authorizer that might be misconfigured or inaccessible, leading to authorization failures.

Advanced Fixes

Advanced Fix 1: Analyze AWS CloudTrail Logs for Authorization Failures

Access AWS CloudTrail in the AWS Management Console. Filter events by 'Event name' such as `Invoke` or `ExecuteApi`.,Look for events where the `errorCode` is `Client.Unauthorized` or `AccessDenied`. Examine the `requestParameters` and `responseElements` to identify the exact API call, principal, and any specific authorization policy that led to the denial.,Cross-reference the CloudTrail logs with API Gateway access logs (if enabled) to get a more complete picture of the request flow and authorizer invocation details.

Advanced Fix 2: Implement a Canary Deployment for Authorizer Changes

For critical APIs, configure a canary deployment for any changes to authorizer logic or configuration. This allows you to route a small percentage of traffic to the new version.,Monitor the canary stage for an increase in 401 errors or authorizer-specific metrics in CloudWatch. If errors spike, roll back the canary deployment immediately.,Gradually shift traffic to the new version after confirming stability, minimizing impact from potential authorization regressions.

FAQs

Q: What is the difference between 401 Unauthorized and 403 Forbidden?

A: A 401 Unauthorized error means the client is not authenticated, implying that valid credentials (like an API key or JWT) were either not provided or were invalid. A 403 Forbidden error means the client is authenticated, but does not have the necessary permissions to access the requested resource, indicating an authorization failure even with valid credentials.

Q: How can I test my API Gateway authorizer independently?

A: In the API Gateway console, navigate to your API, then 'Authorizers'. Select the authorizer you want to test and click the 'Test' button. Provide a sample token (for JWT/Lambda authorizers) or IAM credentials (for AWS_IAM) and view the test result, which will show whether the authorizer returns an 'Allow' or 'Deny' policy.

Q: My API Key works for some endpoints but not others, why?

A: This usually indicates that the API Key requirement is inconsistently applied across your API methods. Check the 'Method Request' settings for each problematic endpoint in the API Gateway console. Ensure 'API Key Required' is enabled for methods that should use the key, and that the API Key is associated with a usage plan linked to the correct API stage(s).

Q: Can CORS preflight requests (OPTIONS) cause a 401 error?

A: Typically, CORS preflight (OPTIONS) requests should not trigger a 401, as they are meant to determine cross-origin policies before the actual request. However, if your API Gateway authorizer is configured to apply to OPTIONS methods, or if the authorizer itself is severely misconfigured, it could potentially block the preflight, leading to unexpected behavior. Ensure OPTIONS methods have no authorizer or API Key requirement.

Related Errors