如何在AWS SAM部署的API Gateway REST API中获取CloudFront地理定位头?
解决步骤
1. 配置API Gateway全局允许传入地理定位头
在你现有的AWS::Serverless::Api资源(即mainBackendApi)的Properties下新增全局头允许配置:
mainBackendApi: Type: AWS::Serverless::Api Properties: StageName: !Ref Stage EndpointConfiguration: Type: EDGE # 新增全局请求头白名单配置 Parameters: gateway.request.headers: "CloudFront-Viewer-Country-Name,CloudFront-Viewer-Country-Region,CloudFront-Viewer-Country-Region-Name,CloudFront-Viewer-City,CloudFront-Viewer-Postal-Code,CloudFront-Viewer-Time-Zone,CloudFront-Viewer-Latitude,CloudFront-Viewer-Longitude,CloudFront-Viewer-Metro-Code" Domain: # 保持你原有Domain配置不变即可 DomainName: !Sub - <hidden> - apiSubDomain: !FindInMap - stageVars - !Ref Stage - apiSubDomain CertificateArn: !Ref customDomainCert Route53: HostedZoneId: <hidden>
2. 给对应接口配置头传入权限
在login函数的ApiEvent配置中,声明允许接口接收这些头:
Resources: login: Type: AWS::Serverless::Function Properties: Handler: src/functions/login.handler Runtime: nodejs14.x Layers: - !Ref dependencies Events: ApiEvent: Type: Api Properties: Method: post Path: /login RestApiId: Ref: mainBackendApi # 新增请求头允许配置,false表示非必传,避免无对应头的请求被拦截 RequestParameters: - method.request.header.CloudFront-Viewer-Country-Name: false - method.request.header.CloudFront-Viewer-Country-Region: false - method.request.header.CloudFront-Viewer-Country-Region-Name: false - method.request.header.CloudFront-Viewer-City: false - method.request.header.CloudFront-Viewer-Postal-Code: false - method.request.header.CloudFront-Viewer-Time-Zone: false - method.request.header.CloudFront-Viewer-Latitude: false - method.request.header.CloudFront-Viewer-Longitude: false - method.request.header.CloudFront-Viewer-Metro-Code: false
3. Lambda中读取头信息
部署完成后,这些地理定位头会自动透传到Lambda的event对象中,所有头的键名会转为小写,读取示例:
exports.handler = async (event) => { // 直接从小写的头字段中取值 const country = event.headers['cloudfront-viewer-country-name']; const city = event.headers['cloudfront-viewer-city']; const timezone = event.headers['cloudfront-viewer-time-zone']; // 后续业务逻辑 return { statusCode: 200, body: JSON.stringify({ message: 'success', location: { country, city, timezone } }) }; };
额外说明
你使用的是EDGE类型的API Gateway,底层默认使用AWS托管的CloudFront分发,不需要额外手动配置CloudFront的地理定位开关,AWS会自动向请求注入对应的地理信息头。如果后续切换为REGIONAL类型API+自建CloudFront的架构,需要额外在CloudFront的源请求策略中勾选需要转发的地理定位头。
内容的提问来源于stack exchange,提问作者aprilmintacpineda
相关产品推荐
相关产品推荐

