使用AWS Gateway API,我可以访问cookie吗?

Bar*_*ing 8 amazon-web-services aws-api-gateway

使用HTTP代理集成我想访问cookie并在json响应中添加一个.那可能吗?

Lor*_*ara 9

要访问后端客户端发送的cookie,您必须设置从方法请求标头到集成请求标头的映射.

这些说明假设您已经在API网关中设置了一个简单的方法.

访问后端的cookie

  1. 在"方法请求"下,创建名为"Cookie"的HTTP请求标头
  2. 在Integration Request下,创建一个名为"Cookie"和"Mapped from"值为的HTTP标头method.request.header.Cookie.
  3. 您可能还需要为此方法设置CORS.请参阅:http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
  4. 部署API并使用浏览器/客户端向API Gateway端点发出请求.您应该看到使用从浏览器发送的Cookie标头值进入HTTP后端的请求.

添加cookie到响应

您可以Set-Cookie以类似的方式为方法配置的集成响应/方法响应端设置响应头.

  1. 在"方法响应"下,创建一个带有名称的Response标头 Set-Cookie
  2. 在Integration Response下,设置带有Response标头Set-Cookie和Mapping值的Header Mappingintegration.response.header.Set-Cookie

请注意,此时,API Gateway仅支持设置单个Set-Cookie响应标头.如果您的后端尝试设置多个Set-Cookie标头,则只会设置最后一个.有关详细信息,请参阅此论坛帖子:https://forums.aws.amazon.com/thread.jspa?messageID = 701434


Max*_*lle 8

如果在API网关方法中选中"使用Lambda代理集成"选项,请求标头将通过event变量传递给Lambda函数.API网关还期望您的回调函数有不同的响应.此响应格式可用于指示Set-Cookie标头.例如:

callback(null, {
    statusCode: 200,
    headers: {'Set-Cookie': 'key=val'},
    body: 'Some response'
})`
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是不需要任何方法请求或方法响应调整.

下面是一个示例Lambda函数,使用此逻辑在每个请求后旋转cookie值.

exports.handler = (event, context, callback) => {

    var cookies = getCookiesFromHeader(event.headers);

    var old_cookie = cookies.flavor;
    var new_cookie = pickCookieFlavor(old_cookie);

    return callback(null, {
        statusCode: 200,
        headers: {
            'Set-Cookie': setCookieString('flavor', new_cookie),
            'Content-Type': 'text/plain'
        },
        body: 'Your cookie flavor was ' + old_cookie + '. Your new flavor is ' + new_cookie + '.'
    });
};

/**
 * Rotate the cookie flavor
 */
function pickCookieFlavor(cookie) {
    switch (cookie) {
        case 'peanut':
            return 'chocolate';
        case 'chocolate':
            return 'raisin and oat';
        default:
            return 'peanut';
    }
}

/**
 * Receives an array of headers and extract the value from the cookie header
 * @param  {String}   errors List of errors
 * @return {Object}
 */
function getCookiesFromHeader(headers) {

    if (headers === null || headers === undefined || headers.Cookie === undefined) {
        return {};
    }

    // Split a cookie string in an array (Originally found http://stackoverflow.com/a/3409200/1427439)
    var list = {},
        rc = headers.Cookie;

    rc && rc.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        var key = parts.shift().trim()
        var value = decodeURI(parts.join('='));
        if (key != '') {
            list[key] = value
        }
    });

    return list;
};


/**
 * Build a string appropriate for a `Set-Cookie` header.
 * @param {string} key     Key-name for the cookie.
 * @param {string} value   Value to assign to the cookie.
 * @param {object} options Optional parameter that can be use to define additional option for the cookie.
 * ```
 * {
 *     secure: boolean // Watever to output the secure flag. Defaults to true.
 *     httpOnly: boolean // Watever to ouput the HttpOnly flag. Defaults to true.
 *     domain: string // Domain to which the limit the cookie. Default to not being outputted.
 *     path: string // Path to which to limit the cookie. Defaults to '/'
 *     expires: UTC string or Date // When this cookie should expire.  Default to not being outputted.
 *     maxAge: integer // Max age of the cookie in seconds. For compatibility with IE, this will be converted to a
*          `expires` flag. If both the expires and maxAge flags are set, maxAge will be ignores. Default to not being
*           outputted.
 * }
 * ```
 * @return string
 */
function setCookieString(key, value, options) {
    var defaults = {
        secure: true,
        httpOnly: true,
        domain: false,
        path: '/',
        expires: false,
        maxAge: false
    }
    if (typeof options == 'object') {
        options = Object.assign({}, defaults, options);
    } else {
        options = defaults;
    }

    var cookie = key + '=' + value;

    if (options.domain) {
        cookie = cookie + '; domain=' + options.domain;
    }

    if (options.path) {
        cookie = cookie + '; path=' + options.path;
    }

    if (!options.expires && options.maxAge) {
        options.expires = new Date(new Date().getTime() + parseInt(options.maxAge) * 1000); // JS operate in Milli-seconds
    }

    if (typeof options.expires == "object" && typeof options.expires.toUTCString) {
        options.expires = options.expires.toUTCString();
    }

    if (options.expires) {
        cookie = cookie + '; expires=' + options.expires.toString();
    }

    if (options.secure) {
        cookie = cookie + '; Secure';
    }

    if (options.httpOnly) {
        cookie = cookie + '; HttpOnly';
    }

    return cookie;
}
Run Code Online (Sandbox Code Playgroud)

  • 可以添加一件事,我试图从CloudFront的请求中获取cookie(我使用lambda作为代理)。Cookie的实际值实际上存储在`event.Records [0] .cf.request.headers.cookie [0] .value`中,因此可能需要稍微更改一下功能才能找到Cookie。 (2认同)