ASP.NET - 如果角色授权失败,则重定向到错误页面

Bra*_*don 21 .net c# authentication asp.net-mvc forms-authentication

我正在使用MVC 3与表单身份验证.在我的控制器或方法上,我正在执行以下操作:

[Authorize (Roles = "developer")]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想检查用户是否已登录,如果没有,请将其返回登录页面.但是,如果该用户的"IsInRole"检查返回false,我希望他们转到另一个类似"未授权"的视图.

完成这样的事情的最佳方法是什么?我希望避免创建一个新的Authorization属性,所以我不必重构整个应用程序中的每个Authorize属性,但如果这是必需的,我将走这条路.

Dar*_*rov 47

覆盖HandleUnauthorizedRequest方法的自定义授权属性可以完成这项工作:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

[MyAuthorize(Roles = "developer")]
public ActionResult Develop()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 你把这个自定义实现放在哪里? (3认同)