【问题标题】:Custom authorization attributes in ASP.NET CoreASP.NET Core 中的自定义授权属性
【发布时间】:2016-07-08 10:49:00
【问题描述】:

我正在研究 asp.net 核心,但我不明白一些事情。 例如在 mvc.net 5 中,我们可以通过从 AuthorizeAttribute 创建类来过滤和授权操作,并将属性设置为如下操作:

public class AdminAuthorize : AuthorizeAttribute {
        public override void OnAuthorization(AuthorizationContext filterContext) {
            base.OnAuthorization(filterContext);
            if (filterContext.Result is HttpUnauthorizedResult)
                filterContext.Result = new RedirectResult("/Admin/Account/Login");
        }
    }

但是在 asp.net core 中我们没有 AuthorizeAttribute ... 如何在 asp.net 核心中为自定义操作设置这样的过滤器?

【问题讨论】:

    标签: c# filter asp.net-core action authorize


    【解决方案1】:

    您可以使用身份验证中间件和Authorize attirbute 重定向登录页面。对于您的情况,也使用AuthenticationScheme 似乎是合理的。

    第一次使用(我假设你想使用cookie中间件)cookie认证中间件:

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "AdminCookieScheme",
                LoginPath = new PathString("/Admin/Account/Login/"),
                AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName="AdminCookies"
            });
    

    然后在此方案中使用Authorizeattribute:

    [Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]
    

    另一种选择是使用UseWhen 将管理员身份验证和默认身份验证分开:

          app.UseWhen(x => x.Request.Path.Value.StartsWith("/Admin"), builder =>
          {
              builder.UseCookieAuthentication(new CookieAuthenticationOptions()
              {
                  LoginPath = new PathString("/Admin/Account/Login/"),
                  AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
                  AutomaticAuthenticate = true,
                  AutomaticChallenge = true
              });
          });
    

    然后只需使用Authorize 属性。

    【讨论】:

    • 还有其他方法吗?
    • 如果你的意思是没有身份验证中间件的另一种方式,我会说“不”用于身份验证。但是对于分支(管理员,默认等),可能还有另一种方式,例如MapWhen
    猜你喜欢
    • 1970-01-01
    • 2021-01-12
    • 2021-03-17
    • 2022-08-19
    • 2021-07-19
    • 1970-01-01
    • 2019-03-10
    • 2020-04-11
    • 2019-07-31
    相关资源
    最近更新 更多