C++ REST SDK Cookies

Tags: ,

Objective

Parse cookies from an http_request and set new cookies in an http_response in C++ REST SDK (Casablanca). This simple example will answer some of the codeplex discussions: How to use cookies with casablanca ? or Is there a cookie demo?. It can be helpful for session management in Casablanca to use a cookie containing a unique session identifier.

Download Parser

parser.h: granada::http::parser header
parser.cc: granada::http::parser cc

Let's cook

Example on how to get and set cookies

Cookies are "passed" to the server in the "Cookie" HTTP request header and are set in the "Set-Cookie" HTTP response header.
In this example we parse the http_request into an unordered_map of cookies then we get and print one of the cookie's content. In the returned response we add a cookie adding it to the "Set-Cookie" header.

void TestController::handle_get(web::http::http_request request){

  // parse cookies
  std::unordered_map cookies = granada::http::parser::ParseCookies(request);

  // print content of cookietest
  auto it = cookies.find("cookie1");
  if (it != cookies.end()){
    std::cout << "content of cookie1 => " << it->second << std::endl;
  };


  http_response response;

  // setting a new cookie
  response.headers().add(U("Set-Cookie"), "cookie2=content2");

  response.set_body("...body...");
  request.reply(response);
}
That's it!

How the parser works

Eample of HTTP headers

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6,de;q=0.4,it;q=0.2
Cache-Control:no-cache
Connection:keep-alive
Cookie:cookie1=content1; cookie2=content2; cookie3=content3A=content3B=content3C
Pragma:no-cache
User-Agent:Mozilla/5.0 (X11; Linux x86_64) ...
1- Get Cookie content from headers
2- Parse each cookie separated by a ";" extract the name of each cookie and its content and insert them into an unordered map:
parsed cookies (unordered map)
    |_ cookie1    => content1
    |_ cookie2    => content2
    |_ cookie3    => content3A=content3B=content3C

Helpful links

Classes References

http_request: web::http::http_request Class Reference
http_headers: web::http::http_headers Class Reference
http_response: web::http::http_response Class Reference

More

HTTP State Management Mechanism: This document defines the HTTP Cookie and Set-Cookie header fields.