UserControl
UserControl

Reputation: 15159

AuthorizeAttribute behavior in ASP.NET MVC when authentication mode is set to Windows

I have a controller protected with AuthorizeAttribute. When the authorization fails i get just an empty page. If i override OnAuthorization() i can see that after calling base.OnAuthorization() filterContext.Result is null (why?). If i override OnException() and set a breakpoint it never hits. Can please someone explain how it's supposed to work? How can i make it redirect to specified page? Where can i inject into to log failed authorization attempts (better not to write custom filter)? I use MVC 3 RC1 if it's important.

Upvotes: 1

Views: 1274

Answers (1)

Levi
Levi

Reputation: 32818

You want to override the AuthorizeAttribute.HandleUnauthorizedRequest method. Here's the default implementation:

protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
    // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
    filterContext.Result = new HttpUnauthorizedResult();
}

You'll instead want to set the Result to be a RedirectResult (or some other result depending on your desired logic). This would also be a good place for logging.

Upvotes: 8

Related Questions