AWS SAM API Gateway:CORS预请求遭默认授权器拦截配置无效
问题重现
配置AWS Serverless API Gateway时,已设置默认授权器,同时开启CORS并将AddDefaultAuthorizerToCorsPreflight设为false,但浏览器发起的OPTIONS预检请求仍被要求授权,返回401状态码。简化后的SAM模板如下:
Resources: myApiGateway: Type: AWS::Serverless::Api Properties: StageName: Staging Cors: AllowMethods: "'*'" AllowHeaders: "'*'" AllowOrigin: "'*'" Auth: Authorizers: aadAuthorizer: FunctionPayloadType: TOKEN FunctionArn: Fn::GetAtt: - authorizerFunctionV1 - Arn DefaultAuthorizer: aadAuthorizer AddDefaultAuthorizerToCorsPreflight: false
可行解决方案
1. 明确指定CORS允许的方法(包含OPTIONS)
将AllowMethods从'*'改为包含OPTIONS的具体方法列表,避免SAM自动生成OPTIONS端点时出现解析问题:
Cors: AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'" AllowHeaders: "'*'" AllowOrigin: "'*'"
2. 手动添加无授权的OPTIONS路由
显式定义覆盖所有路径的OPTIONS端点,并强制跳过授权:
Resources: myApiGateway: Type: AWS::Serverless::Api Properties: StageName: Staging Cors: AllowMethods: "'*'" AllowHeaders: "'*'" AllowOrigin: "'*'" Auth: Authorizers: aadAuthorizer: FunctionPayloadType: TOKEN FunctionArn: !GetAtt authorizerFunctionV1.Arn DefaultAuthorizer: aadAuthorizer AddDefaultAuthorizerToCorsPreflight: false # 手动添加OPTIONS预检路由,跳过授权 PreflightHandler: Type: AWS::Serverless::Function Properties: Handler: index.preflightHandler Runtime: nodejs18.x Events: AllOptions: Type: Api Properties: RestApiId: !Ref myApiGateway Path: "/{proxy+}" Method: OPTIONS Auth: Authorizer: NONE
对应的Lambda handler可以直接返回CORS响应头:
exports.preflightHandler = async (event) => { return { statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "*", "Access-Control-Allow-Headers": "*" }, body: "" }; };
3. 升级SAM CLI到最新稳定版
部分旧版本SAM CLI存在AddDefaultAuthorizerToCorsPreflight配置的回归问题,执行以下命令升级:
pip install --upgrade aws-sam-cli
4. 修正模板中的引号转义问题
模板中"'*'"是HTML转义后的写法,在YAML模板中直接使用"'*'"更规范,避免解析错误:
Cors: AllowMethods: "'*'" AllowHeaders: "'*'" AllowOrigin: "'*'"
内容的提问来源于stack exchange,提问作者Affe
相关产品推荐
相关产品推荐

