【问题标题】:Use multiple same header field in Lambda Proxy Integration在 Lambda 代理集成中使用多个相同的标头字段
【发布时间】:2018-03-17 16:38:57
【问题描述】:

我正在编写一个 Lambda 函数,它在 Python 中返回对 Lambda Proxy Integration 的响应。 API 期望标题是字典。

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

这要求每个头域都是唯一的,所以没有办法使用多个Set-Cookie。 我已经尝试将字典转换为元组列表

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": [ ("headerName": "headerValue"), ... ],
    "body": "..."
}

但 API 网关抱怨 Malformed Lambda proxy response。

知道如何设置同名的标题吗?

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-api-gateway


    【解决方案1】:

    目前无法通过 lambda 集成发送多个 cookie。

    如果您发送多个 set-cookie,那么它将采用最后一个。好吧,这么垃圾的实现就对了。

    参考,How can I send multiple Set-Cookie headers from API Gateway using a proxied Lambda

    让我们看看其他可用的选项,

    Lambda@Edge:

    这是我发现与 Lambda@Edge 合作的结果,

    您可以为查看器响应创建一个 lambda 函数并修改标头以设置 cookie。

    'use strict';
    
    exports.handler = (event, context, callback) => {
       const response = event.Records[0].cf.response;
       const headers = response.headers;
    
       // send via a single header and split it into multiple set cookie here.
       headers['set-Cookie'] = 'cookie1';
       headers['Set-Cookie'] = 'cookie2';
    
       callback(null, response);
    };
    

    API 网关集成请求映射:

    这是我发现并处理集成请求的内容,

    希望对你有帮助。

    【讨论】:

    • 您的 Lambda@Edge 示例不正确,将导致错误。具体来说,它已经过时了。在 L@E 普遍可用前几天,数据结构发生了变化。
    • @Michael-sqlbot。感谢您发现错误(如果有)。 docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/… 仍然具有与我们生产中相同的示例。如果有什么改变,我也想改变。您能指出正确的文档示例吗?我也会修正答案。
    【解决方案2】:

    Lambda@Edge:

    可以这样设置标题:

    response.headers['set-cookie'] = [
      { key: 'Set-Cookie', value: 'cookie1=value1' },
      { key: 'Set-Cookie', value: 'cookie2=value2' },
    ]
    

    https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html#lambda-event-structure-response

    API 网关:

    使用 multiValueHeaders:

    response.multiValueHeaders = {
      "Set-Cookie": [
        'cookie1=value1',
        'cookie1=value1'
      ]
    }
    

    https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

    【讨论】:

    • 我在使用 Lambda@Edge 时遇到错误。挣扎了很多,但无法解决 multiValueHeaders: { 'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}] }
    猜你喜欢
    • 2017-01-16
    • 2018-10-12
    • 2019-02-21
    • 1970-01-01
    • 2017-02-07
    • 2019-08-18
    • 2023-03-15
    • 1970-01-01
    • 2019-09-27
    相关资源
    最近更新 更多