gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:41:00 27 4
gpt4 key购买 nike

我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com