views:

259

answers:

2

By default, ASP.NET's membership provider redirects to a loginUrl when a user is not authorized to access a protected page.

Is there a way to display a custom 403 error page without redirecting the user?

I'd like to avoid sending users to the login page and having the ReturnUrl query string in the address bar.

I'm using MVC (and the Authorize attribute) if anyone has any MVC-specific advice.

Thanks!

+3  A: 

I ended up just creating a custom Authorize class that returns my Forbidden view. It works perfectly.

public class ForbiddenAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                // auth failed, display 403 page
                filterContext.HttpContext.Response.StatusCode = 403;
                ViewResult forbiddenView = new ViewResult();
                forbiddenView.ViewName = "Forbidden";
                filterContext.Result = forbiddenView;
            }
        }

        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        {
            validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
        }
    }
AlexWalker
A: 

Asp.net has had what I consider a bug in the formsauth handling of unauthenticated vs underauthenticated requests since 2.0.

After hacking around like everyone else for years I finally got fed up and fixed it. You may be able to use it out of the box but if not I am certain that with minor mods it will suit your needs.

be sure to report success or failure if you do decide to use it and I will update the article.

http://www.codeproject.com/Articles/39062/Salient-Web-Security-AccessControlModule.aspx

Sky Sanders