C++ REST SDK Cookies

Tags: ,


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");

That's it!

How the parser works

Eample of HTTP headers

Accept-Encoding:gzip, deflate, sdch
Cookie:cookie1=content1; cookie2=content2; cookie3=content3A=content3B=content3C
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


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