KiLa
KiLa

Reputation: 143

Correct way to use cookies in HTTP basic authentication

im trying to implement basic HTTP authentication to my IIS hosted WebAPI service. Im trying to use cookies to send user related data between server and client. This code seems to work when client is Firefox, but if i use IE or Chrome, the cookie is never send back to server.

I have the following.

Im adding the cookie to response message like this... in HttpModule.AuthenticateRequest-event handler...

HttpApplication app = sender as HttpApplication;

HttpResponse response = app.Context.Response;
HttpRequest request = app.Context.Request;

HttpCookie c = new HttpCookie("MyCookie", "Hellou!");
c.Expires = DateTime.Now.AddDays(1);
c.Domain = request.Url.Host;
c.Path = "/";

response.Cookies.Add(c);

...or in controllers POST action:

CookieHeaderValue chv = new CookieHeaderValue("MyCookie", "Hellou");
chv.Expires = DateTime.Now.AddDays(1);
chv.Domain = Request.RequestUri.Host;
chv.Path = "/";

rmsg.Headers.AddCookies(new CookieHeaderValue[] { chv });

Im reading the cookie like this, in HttpModule.AuthenticateRequest-event handler

HttpApplication app = sender as HttpApplication;
HttpRequest request = app.Context.Request;

if (request.Cookies.Count > 0)
{
    HttpCookie c = request.Cookies.Get("MyCookie");
    if (c != null)
    {
        // ...
    }
}

Is the cookie code correct? Is there a way to ensure that the cookie works in all clients?

Upvotes: 3

Views: 6873

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039140

The whole idea of basic authentication is that the username and password of the user are sent by the client on each request in the Authorization header. You do not need any cookies when designing an API.

If you don't want to use basic authentication (because the username and password need to be sent on each request), you could protect your API with token. Take a look at the following article for an example.

Upvotes: 3

Related Questions