Thursday, January 13, 2011

Asp.net HTTP module to force authenticate user via Basic WWW-Authenticate dialogue

Playing around with the available authentication methods I came up with a simple Http module that forces the browser to display the build in credentials form and authenticates the user by simply adding a line in the web.config file.

This is actually a pretty simple class that inherits the IHttpModule interface and hooks up on the web application’s Authenticate request event in order to modify the response headers and reply with a 401 error code.
In order to dictate the browser in showing the build in login form, you’ll have to add the WWW-Authenticate header on the first unauthenticated call.
IE default "request for credentials" dialogue
When the user provides the requested credentials, the module parses the new request and tries to locate the “Authorization” header that should contain a value like the following:

Basic aGVsbG86bGw=

This string contains the username and the password in a username:password format that is provided in a Base64 encoding. To be more specific, aGVsbG86bGw= is the Base64 encoding of the UTF7 string “hello:ll” which means that the username is hello and the password is ll.
As you may understand there is a MAJOR security concern if you decide to adopt such an authentication mechanism. The attacker can sniff the credentials since they are provided in an almost clear text form. You should at least use an ssl to secure the connection between the client and the server.
The module continues with the user validation and then authenticates the user by creating a GenericPrincipal, which is assigned in the HttpContext.Current.User.
In order to activate the module you’ll have to declare it in the system.web/httpModules section of your web.config file by adding a line like the following (I have signed my dll and installed it in the GAC):
<add name="CustomAuthModule" type="Abot.Security.BasicAuthenticationModule, Abot.Security, Version=1.0.0.0, Culture=neutral, PublicKeyToken=69ab320f50ed06d0"/>

The commented source code of the above mentioned IHttpModule is available in the following link:





Note that I have used the #if DEBUG declaration in order to provide logging when the dll is built in debug configuration. The logging mechanism is really simple and is not recommended (I could even characterize it as a very bad practice). If you want to implement robust logging, check out this ScottGu’s blogpost.


No comments: