Using the AWS Gateway API, can I access cookies?

Using HTTP proxy integration. I want to access cookies and add them to json response. Is it possible?

+5
source share
2 answers

To access the cookies sent by the client in your backend, you need to configure the mapping from the method request header to the integration request header.

These instructions assume that you have already installed a simple method in the API gateway.

Accessing cookies in your backend

  • In the method request, create an HTTP request header named Cookie
  • In the integration request, create an HTTP header named "Cookie" and "Mapped from" with the value method.request.header.Cookie .
  • You will also probably need to configure CORS for this method. See: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
  • Expand your API and query your API gateway endpoint using your browser / client. You should see requests coming to your HTTP server with a cookie header sent from the browser.

Add cookie in response

You can set the Set-Cookie response header in the same way to respond to the integration response request / configuration method method.

  • In the Method response, create a Response header named Set-Cookie
  • In the "Configuring an Integration Response" section, matching headers with the Set-Cookie response header and the integration.response.header.Set-Cookie mapping value

Please note that at this time, the Gateway API supports setting only one Set-Cookie response header. If your backend is trying to set multiple Set-Cookie headers, only the last one will be set. See this forum for more details: https://forums.aws.amazon.com/thread.jspa?messageID=701434

+7
source

If you check the "Use Lambda Proxy Integration" checkbox in your API, the request headers will be passed to your Lambda function using the event variable. The Gateway API also expects another response from your callback function. This response format can be used to indicate the Set-Cookie header. eg:.

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

This approach has the advantage that it does not require any method requests or response methods.

Here's a sample Lambda function using this logic to rotate a cookie value after each request.

 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; } 
+3
source

Source: https://habr.com/ru/post/1243644/


All Articles