1
votes

I have a Forms Authenticated web application but I need Basic Authentication on a couple of services which are all located at a specific path (ie. "~/Services/").

I originally tried to add a tag in the web.config with a seperate custom MembershipProvider for the path like so:

  <location path="Services">
    <system.web>
      <authentication mode="None" />
      <authorization>
        <deny users="?" />
      </authorization>
      <membership defaultProvider="ServicesMembershipProvider">
        <providers>
          <add name="DefaultMembershipProvider" type="Company.WebProject.DeviceMembershipProvider" connectionStringName="DefaultConnectionString" applicationName="/" />
        </providers>
      </membership>
      <httpModules>
        <add name="BasicAuthentication" type="Company.WebProject.BasicAuthenticationModule" />
      </httpModules>
    </system.web>
  </location>

But this was throwing errors:

It is an error to use a section registered as allowDefinition= 'MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

So I realised that I wasn't allowed to use the authentication element in a location element.

After reading this article, I then tried hooking into the FormsAuthentication_OnAuthenticate method in the Global.asax. As I need to use Basic Authentication, I tried returning a 401 to prompt the browser for basic auth credentials. Unfortunately, it seems this was causing a redirect to the Forms Authentication log on page (ie. loginUrl).

public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
{
    string path = VirtualPathUtility.ToAppRelative(e.Context.Request.Path);
    if (path.Contains("/Services/"))
    {
        e.Context.Response.StatusCode = 401;
        e.Context.Response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", "CompanyRealm"));
        e.Context.Response.End();                
    }
}

So now I have run out of ideas as to how to implement Basic Auth on a folder in a Forms Authenticated web application.

Does anyone have any idea how to achieve this?

2

2 Answers

0
votes

You can't mix Forms Authentication with Windows Authentication in ASP.NET. You will need to create either a separate application for the two or you will need to implement Forms Authentication and Roles to properly do tiered access.

0
votes

A bit late in the day, but I've posted some code here: Combining Forms Authentication and Basic Authentication

Basically you just need to replace

e.Context.Response.End(); 

with

e.Context.Response.Flush(); 
e.Context.Response.Close(); 

Closing the Response object seems to prevent ASP from overriding the redirect. See the above link for full code.