How to make Authorize attribute return custom 403 error page instead of redirecting to the Logon page

What I would do is subclass AuthorizeAttribute and override its HandleUnauthorizedRequest to return HTTP status code 403 if user is authenticated. I would then add a system.webServer\httpErrors section to my Web.Config to replace the default 403 with my custom page (this last part requires IIS 7+). Here’s how:

public class MyAuthorizeAttribute : AuthorizeAttribute {
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new HttpStatusCodeResult(403);
        else
            filterContext.Result = new HttpUnauthorizedResult();
    } 
}

<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="403" />
      <error statusCode="403" responseMode="ExecuteURL" path="/Error/MyCustom403page" />
    </httpErrors>
  </system.webServer>
</configuration>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)