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

Serverless Go自定义授权器无法获取methodArn及调用Lambda信息

问题分析与解决方案

你遇到的核心问题是:AWS HTTP API(v2)的请求类型授权器默认不会传递methodArn、resource这类REST API(v1)授权器里的字段,因为两者的事件结构和授权逻辑设计不同。你的Serverless配置中使用的是httpApi(即HTTP API),而非传统的REST API,这就是字段为空的原因。


1. 修正Serverless授权器配置

更新serverless.yml,指定HTTP API授权器的载荷版本为2.0,并确保业务端点明确关联该授权器:

provider:
  httpApi:
    authorizers:
      custom:
        functionName: permission_verify
        type: request
        payloadVersion: '2.0'  # 必须指定v2版本载荷,才能获取完整请求上下文
        enableSimpleResponses: true  # 可选,简化授权响应格式

functions:
  permission_verify:
    handler: bin/handlers/permission/verify
    # 可选:确保HTTP API有权调用该Lambda
    permissions:
      - httpApi: '*'

# 示例:将授权器绑定到具体业务端点(根据你的实际路由调整)
  user_detail:
    handler: bin/handlers/user/detail
    events:
      - httpApi:
          path: /users/{id}
          method: GET
          authorizer:
            name: custom
            type: request

2. 替换Go代码的事件结构体类型

HTTP API授权器的事件对应events.APIGatewayV2CustomAuthorizerRequest,而非REST API的APIGatewayCustomAuthorizerRequestTypeRequest。你可以从请求上下文获取路径、方法等信息,手动拼接出methodArn:

import (
	"fmt"
	"os"
	"strings"

	"github.com/aws/aws-lambda-go/events"
)

func Handler(request events.APIGatewayV2CustomAuthorizerRequest) (events.APIGatewayV2CustomAuthorizerSimpleResponse, error) {
	// 从请求上下文提取构建ARN所需的核心字段
	httpCtx := request.RequestContext.Http
	apiId := request.RequestContext.APIID
	stage := request.RequestContext.Stage
	accountId := request.RequestContext.AccountID
	region := os.Getenv("AWS_REGION")

	// 手动拼接标准methodArn格式
	methodArn := fmt.Sprintf("arn:aws:execute-api:%s:%s:%s/%s/%s/%s",
		region,
		accountId,
		apiId,
		stage,
		httpCtx.Method,
		strings.TrimPrefix(httpCtx.Path, "/"),
	)

	// 你的JWT验证逻辑...

	// 返回授权响应(开启enableSimpleResponses后用SimpleResponse格式)
	return events.APIGatewayV2CustomAuthorizerSimpleResponse{
		IsAuthorized: true,
		Context: map[string]interface{}{
			"userId": "xxx", // 可传递自定义上下文到业务函数
		},
	}, nil
}

3. 关键说明

  • HTTP API采用轻量化路由模型,不会自动生成methodArn,但提供了构建ARN所需的所有组件(API ID、阶段、路径、方法等),手动拼接即可满足权限校验需求。
  • 如果仅需要请求的路径和方法,直接从request.RequestContext.Http.Path和request.RequestContext.Http.Method获取即可,无需拼接ARN。
  • 确保Lambda函数的执行角色有lambda:InvokeFunction权限给HTTP API,Serverless框架通常会自动配置,若遇权限问题可手动添加IAM策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:37:45