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

AWS API Gateway仅对指定URL路径启用Basic Authentication的问题

解决AWS API Gateway仅特定路径启用Basic认证的问题

核心问题

你当前的Lambda授权器被绑定到了整个API级别,而非仅目标路径的GET方法,导致所有请求都触发认证校验。

修复步骤

1. 调整授权器的绑定范围(控制台操作)

  • 进入AWS API Gateway控制台,打开你的目标API。
  • 定位到/swagger-ui/open_api.yml资源的GET方法:
    1. 展开左侧导航的路径树,找到/swagger-ui -> open_api.yml。
    2. 点击该资源下的GET方法。
  • 在方法配置页面的「授权」选项中,选择你创建的Lambda授权器。
  • 对其他不需要认证的路径(比如/runApi的POST方法),将「授权」设置改为NONE。

2. 优化Lambda授权器代码(可选,增强鲁棒性)

即使绑定正确,也可以在Lambda代码中加入路径判断,避免误拦截:

def lambda_handler(event, context):
    # 获取请求路径
    resource_path = event['requestContext']['resourcePath']
    
    # 仅对swagger相关路径做认证校验
    if '/swagger-ui/' in resource_path:
        auth_header = event.get('headers', {}).get('Authorization')
        # 替换为你的Basic Auth校验逻辑
        if not auth_header or not validate_basic_credentials(auth_header):
            return generate_iam_policy('anonymous', 'Deny', event['methodArn'])
        return generate_iam_policy('authenticated-user', 'Allow', event['methodArn'])
    else:
        # 非swagger路径直接允许访问
        return generate_iam_policy('anonymous', 'Allow', event['methodArn'])

# 以下是辅助函数示例
def validate_basic_credentials(auth_header):
    # 实现你的用户名密码校验逻辑
    from base64 import b64decode
    try:
        auth_type, encoded = auth_header.split(' ', 1)
        if auth_type.lower() != 'basic':
            return False
        username, password = b64decode(encoded).decode('utf-8').split(':', 1)
        return username == 'your-username' and password == 'your-password'
    except:
        return False

def generate_iam_policy(principal_id, effect, resource):
    return {
        'principalId': principal_id,
        'policyDocument': {
            'Version': '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': effect,
                'Resource': resource
            }]
        }
    }

3. 重新部署API

修改完配置后,务必在API Gateway控制台中点击「部署API」,选择对应的部署阶段,确保配置生效。

内容的提问来源于stack exchange,提问作者Nick G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:27:13