8

If the user is not logged in and they request an action marked [Authorize], then the response is a redirect to the Account/LogOn action (status code 302 Found).

Is there a way to make the response be status code 403 Forbidden instead?

Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
  • Is this for a REST interface? – Chris Kooken Jan 19 '11 at 20:59
  • @Chris: No, but out of curiosity why do you ask? I was writing an HttpPost action for which I simply wanted to forbid the request if the user was not logged in rather than redirecting to the LogOn action. – Daniel Trebbien Jan 19 '11 at 23:22
  • 5
    FYI - [Authorize] *does* send back a 403 Forbidden. The FormsAuthenticationModule traps 403 responses and turns them into redirects to the login page. If you're not using forms authentication, you may want to change the section of Web.config to reflect this so that the FormsAuthenticationModule doesn't run this logic. – Levi Jan 20 '11 at 01:02

2 Answers2

11

Create an action filter that inherits from AuthorizeAttribute. Then override this method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{ 
   Response.StatusCode = 403;
   Response.Status = "Forbidden";
   Response.StatusDescription = "Forbidden";
   Response.End();
   Response.Close();

}
Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
0

If the user is not logged in then the more appropriate status code is 401:Unauthorized. This is what the AuthorizeAttribute returns by default.

FormsAuthenticationModule will catch this return code and convert it into the redirect. If you can disable (or not even load it) then this will be returned to the caller.

Timbo
  • 413
  • 3
  • 6