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

解决AWS Terraform中API Gateway V2 $connect路由未关联Lambda授权器问题

解决API Gateway V2 $connect路由无法关联Lambda授权器的问题

以下是几个排查和修复的关键点:

  • 确认Lambda授权器的URI格式正确
    authorizer_uri必须包含Lambda函数ARN加上/invocations后缀,示例格式:

    authorizer_uri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyAuthorizer/invocations"
    

    遗漏/invocations会导致API Gateway无法正确触发授权器。

  • 添加API Gateway调用Lambda的权限
    必须给API Gateway配置调用授权器Lambda的权限,否则授权请求会被拒绝。用Terraform添加该权限:

    resource "aws_lambda_permission" "apigw_authorizer" {
      statement_id  = "AllowAPIGatewayInvokeAuthorizer"
      action        = "lambda:InvokeFunction"
      function_name = var.lambda_authorizer_name
      principal     = "apigateway.amazonaws.com"
    
      source_arn = "${aws_apigatewayv2_api.api_gateway_websocket.execution_arn}/authorizers/${aws_apigatewayv2_authorizer.authorizer.id}"
    }
    

    同时在路由的depends_on中加入这个权限资源,确保资源创建顺序正确。

  • 显式设置路由的authorization_type
    虽然指定authorizer_id时Terraform会自动推断,但显式设置authorization_type = "CUSTOM"可以避免潜在的自动配置错误:

    resource "aws_apigatewayv2_route" "ConnectRoute" {
      api_id             = aws_apigatewayv2_api.api_gateway_websocket.id
      route_key          = "$connect"
      operation_name     = "ConnectRoute"
      authorizer_id      = aws_apigatewayv2_authorizer.authorizer.id
      authorization_type = "CUSTOM"
      depends_on = [
        aws_apigatewayv2_authorizer.authorizer,
        aws_lambda_permission.apigw_authorizer
      ]
    }
    
  • 验证授权器Lambda的返回格式
    REQUEST类型的授权器必须返回符合API Gateway规范的JSON,示例:

    {
      "principalId": "user_123",
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "execute-api:Invoke",
            "Effect": "Allow",
            "Resource": "${你的API执行ARN}/$connect"
          }
        ]
      },
      "context": {
        "user_role": "admin"
      }
    }
    

    返回格式错误会导致API Gateway无法解析授权结果,Auth字段自然不会填充。

  • 检查identity_sources的参数匹配
    确保客户端连接时,query string中确实携带了authorization参数,和你配置的identity_sources = ["route.request.querystring.authorization"]完全一致(参数名大小写敏感)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:07:53