使用ASP.NET成员资格,如何显示403?

时间:2009-12-04 13:58:16

标签: asp.net-mvc asp.net-membership forms-authentication

默认情况下,当用户无权访问受保护的页面时,ASP.NET的成员资格提供程序会重定向到loginUrl。

有没有办法在不重定向用户的情况下显示自定义403错误页面?

我想避免将用户发送到登录页面并在地址栏中输入ReturnUrl查询字符串。

如果有人有任何针对MVC的建议,我正在使用MVC(和Authorize属性)。

谢谢!

2 个答案:

答案 0 :(得分:3)

我最终只是创建了一个返回我的Forbidden视图的自定义Authorize类。 它运作得很好。

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));
        }
    }

答案 1 :(得分:1)

自从2.0以来,Asp.net已经将我认为是 unauthenticated vs underauthenticated 请求的formauth处理中的错误。

多年来和其他人一样被黑客攻击后,我终于厌倦了并修复了它。您可以开箱即用,但如果不是,我确信使用少量mod可以满足您的需求。

如果您决定使用它,请务必报告成功或失败,我将更新该文章。

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