Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override ASP.NET forms authentication for a single page

In our ASP.NET MVC application, we automatically redirect users to a log-on page via the <authentication> section of <system.web> when they attempt to access an authorized-only page. The problem is that one action in the middle of the application, designed to be used by a tool, needs to return a straight-up HTTP 401 response on bad access. How can I return a real HTTP 401 code without the redirect for this specific action?

like image 483
Benjamin Pollack Avatar asked Jun 02 '09 21:06

Benjamin Pollack


Video Answer


2 Answers

The following solution works, although I'm not at all sure it's optimal:

public class HttpAuthenticationRequiredResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.StatusCode = 401;
        response.AddHeader("WWW-Authenticate", "Basic realm=\"whatever\"");
        response.Flush();
        response.Close();
    }
}

You can then return the above result instead of an HttpUnauthorizedResult to generate the required 401 code. This feels quite klugy to me, however.

like image 115
Benjamin Pollack Avatar answered Oct 29 '22 06:10

Benjamin Pollack


You can have separate <system.web> sections for separate paths. Here's an example:

<configuration>
  <location path="Foo/Bar.aspx">
    <system.web>
      <authorization>
        <allow roles="GoodGuys" />
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>

In this case, the page "Foo/Bar.aspx" is allowed to folks with the GoodGuys role, but denied to all others.

In your case, you might want to allow all without authentication:

<configuration>
  <location path="Foo/Bar.aspx">
    <system.web>
      <authentication mode="None" />
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>
like image 39
Randolpho Avatar answered Oct 29 '22 06:10

Randolpho