Search code examples
c++cmongoose-web-server

mongoose networking library: how to get authenticated user?


I'm using Cesanta mongoose networking library to deploy a embedded server. I enabled http_auth using digest.

How can I know which user logged in?


Solution

  • Your question is somewhat vague, so I'm going to assume that you mainly care about tracking unique users throughout a session, whether through IP address, through authentication credentials, or through some other means.

    Check out the API reference for mg_http_server.h

    https://cesanta.com/docs/http/api-server.html

    Specifically, I think the function "mg_http_parse_header2" is what you are looking for. You should be able to use this function to parse your received HTTP response header for the desired field.

    The code example provided for "mg_http_parse_header2" is almost exactly what you are asking for:

    char user_buf[20];
    char user = user_buf;
    struct mg_str hdr = mg_get_http_header(hm, "Authorization");
    mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf));
    // ... do something useful with user
    if (user != user_buf) {
      free(user);
    }
    

    Their example shows how you might extract user information from the Authorization field in a HTTP header. Wikipedia has a list of standard request fields if you would like to tailor the example to your own application:

    https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

    For instance, the "Forwarded" field gives information to identify the originating IP address of the client. The "Authorization" field contains the username and password in an easily recoverable format, so keep in mind that HTTPS provides an extra layer of security whereas plain HTTP presents a potential vulnerability.