简体   繁体   English

覆盖MVC5中的默认[Authorize]行为?

[英]Overriding default [Authorize] behavior in MVC5?

I am wanting to override the default behavior of the [Authorize] attribute. 我想覆盖[Authorize]属性的默认行为。 I found this similar question but it is very old and MVC has had a few iterations since it was published. 我发现了类似的问题,但是它很老,自发布以来,MVC已经进行了几次迭代。

I would prefer not to create a separate 'custom' attribute class and apply that attribute on all controllers/actions in order to just send an unauthorized request to a separate controller/action. 我宁愿不要创建单独的“自定义”属性类并将该属性应用于所有控制器/动作,以便仅将未经授权的请求发送到单独的控制器/动作。 I would like to be able to do this globally and affect all the controllers/actions that are already configured with an [Authorize] attribute. 我希望能够在全局范围内执行此操作,并影响已经使用[Authorize]属性配置的所有控制器/动作。

Is this possible? 这可能吗?

Ok. 好。 Since there isn't a way to overrride the [Authorize] attribute, globally and in place, here is how I got it done. 由于没有一种方法可以在全局和适当位置覆盖[Authorize]属性,因此这是我完成的方法。

Create a new custom AuthorizeAttribute class in the global namespace for your application (I called mine CustomAuthorizeAttribute ). 在您的应用程序的全局命名空间中创建一个新的自定义AuthorizeAttribute类(我称为mine CustomAuthorizeAttribute )。 I placed this class file in a folder called Extend (its where I put all my custom classes when extending the MVC framework) and made sure the namespace is the same as the root namespace for my application (this way all controllers can 'see' it). 我将这个类文件放在一个名为Extend的文件夹中( Extend MVC框架时,我在其中放置了所有自定义类),并确保该名称空间与我的应用程序的根名称空间相同(这样,所有控制器都可以“查看”它) )。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CustomProject
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            System.Web.Routing.RouteValueDictionary rd;
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                rd = new System.Web.Routing.RouteValueDictionary(new { action = "NotAuthorized", controller = "Error" });
            }
            else
            {
                //user is not authenticated
                rd = new System.Web.Routing.RouteValueDictionary(new { action = "Login", controller = "Account" });
            }
            filterContext.Result = new RedirectToRouteResult(rd);
        }
    }
}

My CustomAuthorizeAttribute takes into account authenticated user scenarios and reroutes/redirects appropriately. 我的CustomAuthorizeAttribute考虑了经过身份验证的用户方案,并适当地重新路由/重定向。

You then need to add the [CustomAuthorize(Roles="Admin")] (use the roles that you have configured for your application) to your controllers and/or actions that you want to scrutinize. 然后,您需要将[CustomAuthorize(Roles="Admin")] (使用为应用程序配置的角色)添加到要检查的控制器和/或操作中。

In addition, I created an ErrorController to handle errors and added a "NotAuthorized" action for my needs. 另外,我创建了一个ErrorController来处理错误,并根据需要添加了“ NotAuthorized”操作。 You can certainly extend this if you like. 如果愿意,您当然可以扩展此范围。 Maybe include some logging? 也许包括一些日志记录?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HypeKick.BankUI.Controllers
{
    public class ErrorController : Controller
    {
        //
        // GET: /Error/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult NotAuthorized()
        {
            return View();
        }
}
}

Don't forget to create the necessary views! 不要忘记创建必要的视图!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM