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

API Gateway自定义授权器:定制未授权响应及设置429状态码与消息

API Gateway Custom Authorizers: Custom Unauthorized Responses & 429 Status Code Setup

Hey there! Let's tackle your two questions about API Gateway custom authorizers clearly:

1. Can I customize the response message and status code for unauthorized scenarios in an API Gateway custom authorizer?

Absolutely you can! The level of customization depends on which type of custom authorizer you're using:

  • Lambda Custom Authorizers: This is the most flexible option. Instead of throwing a generic error when authorization fails, you construct a structured deny response that includes your desired statusCode, custom body, and even response headers. API Gateway will respect this structure and return your custom response instead of the default 401/403.
  • JWT Authorizers: While these are rule-based (matching JWT claims against your configured rules), you can still set a custom unauthorized response directly in the API Gateway console or via CloudFormation. You don't need to write code—just specify the status code and message in the "Unauthorized Response" settings.

2. How do I set a 429 status code and return a custom message in an API Gateway custom authorizer?

429 (Too Many Requests) is typically for rate limiting, and you can implement this logic directly in a Lambda custom authorizer. Here's how to do it for both REST APIs and HTTP APIs:

For REST APIs

Your Lambda function needs to return a deny policy along with a response object that defines the 429 status and custom content. Example Node.js code:

exports.handler = async (event) => {
    // Replace this with your actual rate-limiting/authorization logic
    const hasExceededRateLimit = true; // Simulate hitting rate limit

    if (hasExceededRateLimit) {
        return {
            principalId: 'rate-limited-user',
            policyDocument: {
                Version: '2012-10-17',
                Statement: [
                    {
                        Action: 'execute-api:Invoke',
                        Effect: 'Deny',
                        Resource: event.methodArn
                    }
                ]
            },
            response: {
                statusCode: 429,
                headers: {
                    'Content-Type': 'application/json',
                    'X-RateLimit-Limit': '100', // Optional: Include rate limit details
                    'X-RateLimit-Remaining': '0'
                },
                body: JSON.stringify({
                    message: 'Too many requests—please try again in 1 minute.',
                    errorCode: 'RATE_LIMIT_EXCEEDED'
                })
            }
        };
    }

    // Return allow policy if authorization passes
    return {
        principalId: 'authorized-user',
        policyDocument: {
            Version: '2012-10-17',
            Statement: [
                {
                    Action: 'execute-api:Invoke',
                    Effect: 'Allow',
                    Resource: event.methodArn
                }
            ]
        }
    };
};

For HTTP APIs

The response format is simpler—you just need to set isAuthorized to false along with your custom status code and body:

exports.handler = async (event) => {
    const hasExceededRateLimit = true; // Simulate rate limit hit

    if (hasExceededRateLimit) {
        return {
            isAuthorized: false,
            statusCode: 429,
            body: JSON.stringify({
                message: 'You\'ve made too many requests. Please wait and try again.'
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }

    return { isAuthorized: true };
};

A quick note: Make sure your Lambda execution role has the necessary permissions to be invoked by API Gateway, and that you've correctly configured the authorizer in your API Gateway settings (selecting the right Lambda function, setting the correct authorizer type, etc.).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:48:38