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

如何为AWS Serverless Node.js应用的httpApi配置自定义授权器

问题描述

我使用Serverless Framework创建了Node.js REST API,应用结构如下:

service: aws-node-express-api

frameworkVersion: "4"

provider:
  name: aws
  runtime: nodejs20.x

functions:
  api:
    handler: handler.handler
    events:
      - httpApi: "*"

我已经开发了一个独立的自定义认证服务,希望将其作为授权器集成到当前应用中,但配置httpApi时总是出现语法错误,也找不到相关使用示例。

如果使用http事件,我可以轻松完成配置:

privateEndpoint:
    handler: handler.privateEndpoint
    events:
      - http:
          path: api/private
          method: post
          authorizer: auth
          cors: true
解决方案

httpApi(对应AWS API Gateway v2)的授权器配置语法与传统http(API Gateway v1)存在差异,以下是两种可行的集成方式:

1. 集成独立部署的自定义认证服务(通过ARN引用)

若你的认证服务已独立部署到AWS,直接通过其Lambda函数ARN进行配置:

functions:
  api:
    handler: handler.handler
    events:
      - httpApi:
          path: /api/private
          method: post
          authorizer:
            type: request
            identitySource: $request.header.Authorization
            authorizerId: arn:aws:lambda:us-east-1:123456789012:function:your-auth-service-function
          cors: true

2. 在当前服务内定义授权器函数并关联

若授权器函数与API处于同一个Serverless服务中,可先定义授权器函数,再关联到API事件:

service: aws-node-express-api

frameworkVersion: "4"

provider:
  name: aws
  runtime: nodejs20.x

functions:
  api:
    handler: handler.handler
    events:
      - httpApi:
          path: /api/private
          method: post
          authorizer:
            name: authFunction
            type: request
            identitySource: $request.header.Authorization
          cors: true
  # 自定义授权器函数
  authFunction:
    handler: auth.handler

关键配置说明

  • type: 授权器类型,自定义Lambda授权器可选择request(请求型)或jwt(JWT型,适用于基于JWT的认证场景)
  • identitySource: 指定从请求的哪个位置获取认证凭证,例如$request.header.Authorization表示从请求头的Authorization字段提取
  • authorizerId/name: 前者填写已存在的授权器ARN,后者填写当前服务内的授权器函数名称

注意:若之前使用httpApi: "*"通配所有路径,需改为具体路径才能配置授权规则,通配路径无法单独设置授权逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:34:56