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?