R – IIS7 – Password Protect Development Server

asp.net-mvciis-7passwords

I have a development server running IIS 7.0 with an ASP.NET MVC Web Application, that authenticates using Forms Authentication/Membership.

I need to be able to prevent unauthorized users from viewing this site. Our customers however should be able to enter a simple username/password to gain access.

After they do so, they should be able to interact with the web application using Forms Authentication as if they just came to an unprotected site.

Any suggestions?

Best Answer

My previous answer said forms auth and basic http auth could live side by side in II7 integrated mode. I was completely wrong and have since made a simple solution.

Using a custom HttpModule you can add basic auth along side regular forms auth

public class CustomBasicAuthHttpModule : IHttpModule
{
    private HttpApplication httpApplicationContext;

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        this.httpApplicationContext = context;
        context.BeginRequest += this.OnBeginRequest;
        context.EndRequest += this.OnEndRequest;
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        // your logic of checking Auth header goes here
        if (this.httpApplicationContext.Request.Headers["Authorization"] != "Basic base64-encoded-user:pass")
        {
            this.httpApplicationContext.Response.StatusCode = 401;
            this.httpApplicationContext.Response.End();
        }
    }

    private void OnEndRequest(object sender, EventArgs e)
    {
        if (this.httpApplicationContext.Response.StatusCode == 401)
        {
            this.httpApplicationContext.Response.AddHeader("WWW-Authenticate", "Basic");
        }
    }

then in your web.config

  <system.webServer>
    <modules>
      <add name="CustomBasicAuthHttpModule" type="Namespace.CustomBasicAuthHttpModule, AssemblyName"/>
    </modules>
  </system.webServer>