如何在ASP.NET Core中重写HandleUnauthorizedRequest

时间:2016-11-06 04:37:19

标签: c# asp.net-core asp.net-core-mvc asp.net-core-identity

我正在将我的项目迁移到asp.net核心,而且我一直在为我的控制器迁移我的CustomAuthorization属性。这是我的代码。

public class CustomAuthorization : AuthorizeAttribute
{
    public string Url { get; set; }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
        }
        else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "AcessDenied"
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

然后我将它用于我的控制器

[CustomAuthorization(Url = "/Admin/Account/Login", Roles = "Admin")]
public abstract class AdminController : Controller { }

所以,基本上我可以在不满足角色时使用它重定向到不同的登录页面。我有几个区域,每个区域都有不同的登录页面。我尝试使用 CookieAuthenticationOptions 这样的

services.Configure<CookieAuthenticationOptions>(options =>
{
    options.AuthenticationScheme = "Admin";
    options.LoginPath = "/Admin/Account/Login";
});

然后在我的管理员控制器上

[Area("Admin")]
[Authorize(ActiveAuthenticationSchemes = "Admin", Roles = "Admin")]

但是在我登录后,它仍然无法进入。

1 个答案:

答案 0 :(得分:1)

我在我的一个项目中做了类似的事情。这个答案不是使用AuthorizeAttribute;但它可能有助于一些人从谷歌搜索登陆。 在我的情况下,我使用它来基于自定义逻辑进行授权。

首先是我的自定义属性类:

[ServiceFilter(typeof (CustomAuthorizationAttribute))]

我像这样装饰我的控制器:

public void ConfigureServices(IServiceCollection services)
{
     // Add framework services.
     services.AddMvc();

   // my other stuff that is not relevant in this post

     // Security
     services.AddTransient<CustomAuthorizationAttribute>();
 }

然后在我的启动课程中

const DummyLink = ({onClick, children, props}) => (
    <a href="#" onClick={evt => {
        evt.preventDefault();
        onClick && onClick();
    }} {...props}>
        {children}
    </a>
);