c# - 在 ASP.NET MVC 中重定向未经授权的 Controller

标签 c# asp.net-mvc redirect authorization

我在 ASP.NET MVC 中有一个 Controller ,我已将其限制为管理员角色:

[Authorize(Roles = "Admin")]
public class TestController : Controller
{
   ...

如果不属于管理员角色的用户导航到此 Controller ,他们会看到一个空白屏幕。

我想做的是将它们重定向到显示“您需要处于管理员角色才能访问此资源”的 View 。

我想到的一种方法是检查 IsUserInRole() 上的每个操作方法,如果不在角色中,则返回此信息 View 。但是,我必须将它放在每个 Action 中,这会破坏 DRY 原则并且显然维护起来很麻烦。

最佳答案

创建一个基于 AuthorizeAttribute 的自定义授权属性并重写 OnAuthorization 以执行您希望如何完成的检查。通常情况下,如果授权检查失败,AuthorizeAttribute 会将过滤结果设置为 HttpUnauthorizedResult。您可以将其设置为(错误 View 的)ViewResult。

编辑:我有几篇博客文章更详细:

例子:

    [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
    public class MasterEventAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The name of the master page or view to use when rendering the view on authorization failure.  Default
        /// is null, indicating to use the master page of the specified view.
        /// </summary>
        public virtual string MasterName { get; set; }

        /// <summary>
        /// The name of the view to render on authorization failure.  Default is "Error".
        /// </summary>
        public virtual string ViewName { get; set; }

        public MasterEventAuthorizationAttribute()
            : base()
        {
            this.ViewName = "Error";
        }

        protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
        {
            validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
        }

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

            if (AuthorizeCore( filterContext.HttpContext ))
            {
                SetCachePolicy( filterContext );
            }
            else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
            {
                // is authenticated and is in the SuperUser role
                SetCachePolicy( filterContext );
            }
            else
            {
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
            }

        }

        protected void SetCachePolicy( AuthorizationContext filterContext )
        {
            // ** 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 */);
        }


    }

关于c# - 在 ASP.NET MVC 中重定向未经授权的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/977071/

相关文章:

c# - 如何模仿URI查询

c# - 对象不是响应消息模型的原语

asp.net-mvc - 在 ASP.NET MVC 中动态检索 Analysis Services (SSAS) 多维数据集的最佳选择

redirect - Google认为我的首页是斜线

c# - Null Check 运算符不适用于 WebOperationContext.Current?.IncomingRequest

ASP.NET MVC : Pass list of objects from Controller to View

c# - 如何用连字符实现 asp.net mvc Action 名称?

php - PayUMoney 集成重定向到本地主机

unit-testing - 测试重定向 CakePHP 2.0

c# - Caliburn Micro MVVM : Handling data exchange from one View/ViewModel to other ones