I am using Apigee/ Edge extract variables policy.
Say the header looks like:
Cookie: theme=light; sessionToken=abc123
I tried the following in extract variable proxy but it doesn't seem to work.
<Header name="Cookie"> <Pattern ignoreCase="true">theme={theme}; sessionToken={token}</Pattern> </Header>
Does the sequence of parameters (theme, sessionToken) matter? How about extra spaces, do I need to account for that?
Solved! Go to Solution.
Hi @Gagan Arora, @David Allen's answer prints all headers. Here is the JavaScript code to parse the Cookie header into variables (like cookie.theme and cookie.sessionToken), using David's pattern:
var cookieHeaderStr = context.getVariable("request.header.Cookie"); cookieHeaderStr.split("; ").forEach(function(cookieStr) { if (cookieStr) { var sections = cookieStr.split("="); // set variable for each cookie context.setVariable("cookie." + sections[0], sections[1]); } });
Using ExtractVariables is generally not a good solution for Cookie headers. It is hard to guarantee the exact fields and exact order that the fields will be presented. Better solution is to use a Javascript policy, split on semicolon, and then handle each string in the resulting array.
yep. And @Gagan Arora , see also this article.
Here is a JSC snippet which dumps all the values for all headers in a request:
var headerNames = context.getVariable("request.headers.names") + ""; headerNames.split(", ").forEach(function(headerName) { if (headerName) { var headerValues = context.getVariable("request.header." + headerName) + ""; headerValues.split(",").forEach(function(headerValue) { print(headerName + ":" + headerValue); }); } });
This works for multi-value headers, but not the Cookie header that Gagan is asking about.
Yep, substitute the ; for the , on the split for cookies... then split on = to get the name value of the cookie. Good catch Mike!
Hi @Gagan Arora, @David Allen's answer prints all headers. Here is the JavaScript code to parse the Cookie header into variables (like cookie.theme and cookie.sessionToken), using David's pattern:
var cookieHeaderStr = context.getVariable("request.header.Cookie"); cookieHeaderStr.split("; ").forEach(function(cookieStr) { if (cookieStr) { var sections = cookieStr.split("="); // set variable for each cookie context.setVariable("cookie." + sections[0], sections[1]); } });
Here's another approach to handle multi-value headers posted by @Dino.