Wednesday, December 17, 2008

HTTP Basic Authentication and Realms

One of the most well known features of HTTP is Basic Authentication. You most probably know how to implement a basic authentication scheme in HTTP if you spent enough time in web development. You usually add a response status code of 401 (unauthorized) and let the web browser prompt the user for authentication. Then the browser will resubmit the authentication header with every subsequent request under the same domain name.

However, using this simple scheme, one must assume that all requests under the same domain name are accessible to the same people (the concept of roles). Suppose that you want to allow user_1 to access a part of the site with his credentials, and user_2 to access another part with OTHER credentials. Using this simple scheme, it can't be done because the whole site is assumed by the browser to be one unit. A user is either authenticated to access the whole site or not at all.

The solution to this problem is using the 'WWW-Authenticate' response header and the 'realm' keyword. This keyword simply tells the client that authentication is needed for a certain realm (or part) of the website.
WWW-Authenticate: Basic realm="site"

If the browser already has an authentication header for that realm, it will resubmit it. otherwise, it won't just submit any authentication header just because it belongs to that domain name. If it doesn't have the authentication header specific to that realm, it will re-prompt the user again for authentication. i.e. If a subsequent response has a header like this:
WWW-Authenticate: Basic realm="administration"

The browser won't resubmit the authentication header of "site" realm. It will re-prompt the user for "administration" realm authentication.

No comments: