HTTP2 Cookies

Microchip TCP/IP Stack

Microchip TCP/IP Stack Help
HTTP2 Cookies

By design, HTTP is a session-less and state-less protocol; every connection is an independent session with no relation to another. Cookies were added to the protocol description to solve this problem. This feature allows a web server to store small bits of text in a user's browser. These values will be returned to the server with every request, allowing the server to associate session variables with a request. Cookies are typically used for more advanced authentication systems. 

Best practice is generally to store the bulk of the data on the server, and store only a unique identifier with the browser. This cuts down on data overhead and ensures that the user cannot modify the values stored with the session. However, logic must be implemented in the server to expire old sessions and allocate memory for new ones. If sensitive data is being stored, it is also important that the identifier be random enough so as to prevent stealing or spoofing another user's cookies.

Retrieving Cookies

In the HTTP2 server, cookies are retrieved automatically. They are stored in curHTTP.data, just as any other GET form argument or URL parameter would be. The proper place to parse these values is therefore in the HTTPExecuteGet callback using the HTTPGetArg or HTTPGetROMArg functions to locate the values. 

This model consumes some of the limited space available for URL parameters. Ensure that cookies do not consume more space than is available (as defined by HTTP_MAX_DATA_LEN) and that they will fit after any data that may be submitted via a GET form. If enough space is not available, the cookies will be truncated.

Setting Cookies

Cookies can be set in HTTPExecuteGet or HTTPExecutePost. To set a cookie, store the name/value pairs in curHTTP.data as a series of null-terminated strings. Then set, curHTTP.hasArgs equal to the number of name/value pairs to be set. For example, the following code sets a cookie indicating a user's preference for a type of cookie:

void HTTPExecuteGet(void)
{
    ...

    // Set a cookie
    strcpypgm2ram((char*)curHTTP.data, (ROM char*)"flavor\0oatmeal raisin");
    curHTTP.hasArgs = 1;

    ...
}

After this, all future requests from this browser will include the parameter "flavor" in curHTTP.data, along with the associated value of "oatmeal raisin".

Microchip TCP/IP Stack 5.42.08 - June 15, 2013
Copyright © 2012 Microchip Technology, Inc.  All rights reserved.