ASP.NET - 重定向到错误页面,如果角色授权失败 [英] ASP.NET - Redirect to Error Page if Roles Authorization Fails
问题描述
我使用MVC 3与窗体身份验证。在我的控制器或方法,我做了以下内容:
I am using MVC 3 with Forms Authentication. On my controller or methods, I am doing the following:
[Authorize (Roles = "developer")]
在这种情况下,我要检查,如果用户登录,如果没有,他们返回到登录页面。但是,如果IsInRole检查该用户返回假的,我希望他们去了不同的看法,说类似未授权。
In this situation, I want to check if the user is logged in and if not, return them to the login page. However, if the 'IsInRole' check for that user returns false, I want them to go to a different view that says something like 'Not authorized'.
什么是完成这样的事情的最好方法是什么?我希望避免建立新的授权属性,所以我没有必要重构在我的整个应用程序的每个授权属性,但如果是需要什么,我会走这条路。
What is the best way to accomplish something like this? I was hoping to avoid creating a new Authorization attribute so I didn't have to refactor every Authorize attribute in my entire application, but if that is what is required, I will go that route.
推荐答案
自定义授权属性重写<一href="http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.handleunauthorizedrequest.aspx">HandleUnauthorizedRequest方法可以做的工作:
A custom authorize attribute overriding the HandleUnauthorizedRequest method could do the job:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// The user is not authenticated
base.HandleUnauthorizedRequest(filterContext);
}
else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
// The user is not in any of the listed roles =>
// show the unauthorized view
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
然后:
[MyAuthorize(Roles = "developer")]
public ActionResult Develop()
{
...
}
这篇关于ASP.NET - 重定向到错误页面,如果角色授权失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!