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

如何在Serverless Auto Swagger中添加Cognito认证(Node.js)

Serverless Auto Swagger 集成Cognito认证及Swagger UI授权配置

一、集成Cognito认证到Serverless Auto Swagger

1. 为函数配置Cognito授权器

在serverless.yml的函数定义中,给需要认证的API添加Cognito授权器配置,指定用户池ARN和身份来源:

functions:
  yourProtectedFunction:
    handler: src/handlers/protected.handler
    events:
      - http:
          path: /protected/resource
          method: get
          authorizer:
            name: cognitoAuthorizer
            arn: arn:aws:cognito-idp:${self:provider.region}:${aws:accountId}:userpool/${self:custom.userPoolId}
            identitySource: method.request.header.Authorization
            type: token

注:${self:custom.userPoolId}需要在custom区块中提前定义,或者直接替换为你的Cognito用户池ID。

2. 在Auto Swagger中声明认证方案

在serverless.yml的custom > autoSwagger区块中,添加Swagger安全定义,关联你的Cognito用户池:

custom:
  userPoolId: "your-cognito-user-pool-id"
  autoSwagger:
    swaggerSecurityDefinitions:
      cognitoAuth:
        type: apiKey
        name: Authorization
        in: header
        x-amazon-apigateway-authtype: cognito_user_pools
        x-amazon-apigateway-authorizer:
          type: cognito_user_pools
          providerARNs:
            - arn:aws:cognito-idp:${self:provider.region}:${aws:accountId}:userpool/${self:custom.userPoolId}

二、解决Swagger UI授权区域为空的问题

要让Swagger UI显示授权选项,需要给API路径绑定安全规则,有两种方式:

1. 单个API绑定授权规则

在函数的http事件配置中,添加swagger.security字段,关联之前定义的cognitoAuth:

events:
  - http:
      path: /protected/resource
      method: get
      authorizer: cognitoAuthorizer
      swagger:
        security:
          - cognitoAuth: []

2. 全局绑定授权规则

如果所有API都需要认证,可以在autoSwagger中添加全局安全规则,避免逐个配置:

custom:
  autoSwagger:
    swaggerSecurity:
      - cognitoAuth: []

验证效果

部署服务后,打开Serverless Auto Swagger生成的UI页面,顶部会出现Authorize按钮。点击按钮后,输入格式为Bearer <你的Cognito令牌>的内容,即可完成授权,之后访问需要认证的API时会自动携带令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:37:20