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

为API Gateway添加Lambda授权器后出现CORS错误求助

解决API Gateway添加Lambda授权器后的CORS跨域问题

问题根源

添加Lambda授权器后浏览器出现CORS错误的核心原因有两个:

  • OPTIONS预请求被授权器拦截:浏览器发起的OPTIONS预请求默认不带Authorization头,会触发Lambda授权器返回isAuthorized: false,此时API Gateway返回的403响应未附带配置的CORS头,导致浏览器判定跨域违规。
  • 授权失败响应缺少CORS头:正常请求授权失败时,API Gateway默认返回的4xx错误响应也不会自动添加CORS头,同样会被浏览器拦截。

解决方案

1. 让OPTIONS请求跳过授权器

在Serverless配置中,为OPTIONS方法单独设置无授权策略,避免预请求被拦截。修改serverless.yaml,在functions下添加API Gateway事件配置:

functions:
  function1:
    handler: index.handler
    events:
      - httpApi:
          path: /your-api-path  # 替换为实际API路径
          method: GET
          authorizer:
            name: function1
            type: request
      - httpApi:
          path: /your-api-path
          method: POST
          authorizer:
            name: function1
            type: request
      - httpApi:
          path: /your-api-path
          method: OPTIONS
          authorizer:
            type: none  # OPTIONS请求跳过授权

2. 修复Lambda授权器的边界处理

当前代码在authorization头不存在或格式错误时会直接报错,导致不必要的授权失败。修改代码补充边界判断:

const jwt= require("jsonwebtoken");
const { jwtDecode } = require('jwt-decode');

module.exports.handler = async (event) => {
  try {
    // 检查Authorization头是否存在
    if (!event.headers['authorization']) {
      return { isAuthorized: false };
    }
    
    const authHeaders = event.headers['authorization'].split(' ');
    // 验证Bearer令牌格式
    if (authHeaders.length !== 2 || authHeaders[0] !== 'Bearer') {
      return { isAuthorized: false };
    }
    
    jwt.verify(authHeaders[1], process.env.JWT_KEY);
    const tokenData = jwtDecode(authHeaders[1]);
    
    if (['admin', 'moderator', 'user'].includes(tokenData.role)) {
      return { isAuthorized: true };
    }
    return { isAuthorized: false };  
  } catch (err) {
    return { isAuthorized: false };
  }
}

3. 修正CORS配置细节

检查serverless.yaml中的CORS配置,去掉allowedOrigins里的冗余斜杠(避免匹配失败):

provider:
  name: aws
  httpApi:
    cors:
      allowedOrigins:
        - https://prod.example.com
        - https://api.example.com
        - http://localhost:3000  # 移除末尾斜杠
      allowedHeaders:
        - Content-Type
        - Authorization
      allowedMethods:
        - GET
        - OPTIONS
        - POST
      maxAge: 6000

4. 配置错误响应的CORS头

如果需要授权失败时返回带CORS头的错误响应,可在API Gateway控制台操作:

  • 进入目标HTTP API,选择「网关响应」
  • 找到403 Forbidden和401 Unauthorized类型,添加自定义响应头:
    • Access-Control-Allow-Origin:设置为前端域名(生产环境不建议用*)
    • Access-Control-Allow-Headers:Content-Type,Authorization

验证步骤

  1. 重新部署应用:serverless deploy --stage prod
  2. 用浏览器开发者工具查看OPTIONS请求的响应头,确认包含Access-Control-Allow-Origin等CORS字段
  3. 测试无效令牌场景,检查浏览器是否再出现CORS错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:13