Password Protect Staging Sites IIS7
group commerce api documentation
If you have a website you are ready to launch and still want some client feedback on it and want to keep pesky search indexes away it is easiest to give a user/pass to your client for them to look at it. Perhaps it is on a staging domain, yes there is the robots=”no follow”, but sometimes you really want the staging site to be private.
With IIS 6 you would set forms authentication in your web.config and go into IIS and turn off anonymous authentication and bind it to a windows user account. This worked well, although a little time consuming setting up the account, permissions, password management, however, one of the consequences of the tighter integration with the .net runtime and IIS was the loss of the ability to have both password protect and forms authentication on a site. For a variety of reasons this makes sense.
Included is an HttpModule that will enable you to quickly password protect a site and still retain all the forms authentication behavior.
<appSettings>
<add key="br-username" value="bob" />
<add key="br-password" value="sally" />
</appSettings>
/.../
<!--this second is defined here for cassini-->
<httpModules>
<add name="PasswordProtect"
type="BillRob.Web.PasswordProtectHttpModule, BillRob.Web" />
/.../
<!-- this section is for iis 7 -->
<modules runAllManagedModulesForAllRequests="true">
<add name="PasswordProtect"
type="BillRob.Web.PasswordProtectHttpModule, BillRob.Web" />
And add a reference to BillRob.Web. The HttpModule itself is very basic, it hooks the BeginRequest, as to not interfere with any other processing. If the password app settings are defined, it will check the Authorization header of the incoming request and check it against a basic digest hash. (Does anyone see how unsecured this process is?) All modern browsers support this type of WWW-Authenticate header.
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
var data = String.Format("{0}:{1}", username, password);
var correctHeader = "Basic " +
Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
string securityString = request.Headers["Authorization"];
if (securityString == null)
goto forceRedirect;
if (securityString != correctHeader)
goto forceRedirect;
return;
forceRedirect:
var host = request.Url.Host.ToLower();
response.AddHeader("WWW-Authenticate",
String.Format(@"Basic realm=""{0}""", host));
response.StatusCode = 401;
response.End();
}
Yeah, that’s right, I used a goto statement. Here is a zip of the full sample application and a prebuilt assembly.
PasswordProtectSites.rar