How to extract multiple variables from a multi value header?

Not applicable

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 Solved
1 7 2,729
1 ACCEPTED 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]);
  }
});

View solution in original post

7 REPLIES 7

@Gagan Arora

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.

Not applicable

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]);
  }
});

Not applicable

Here's another approach to handle multi-value headers posted by @Dino.