简体   繁体   English

ASP.NET Core中的自定义授权属性

[英]Custom authorization attributes in ASP.NET Core

i'm working on asp.net core and i don't understand some things. 我正在研究asp.net核心,我不了解一些事情。 for example in mvc.net 5 we can filter and authorize action with create class from AuthorizeAttribute and set attribute to actions like this: 例如,在mvc.net 5中,我们可以使用AuthorizeAttribute中的create class过滤和授权操作,并将属性设置为这样的操作:

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");
        }
    }

but in asp.net core we don't have AuthorizeAttribute ... how can i set filter like this in asp.net core for custom actions ? 但是在asp.net核心中我们没有AuthorizeAttribute ...如何在asp.net核心中为自定义操作设置这样的过滤器?

You can use authentication middleware and Authorize attirbute to redirect login page. 您可以使用身份验证中间件和Authorize attirbute来重定向登录页面。 For your case also using AuthenticationScheme seems reasonable. 对于您的情况,使用AuthenticationScheme似乎也是合理的。

First use(i assume you want use cookie middleware) cookie authentication middleware: 首次使用(我假设您要使用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"
        });

and then use Authorize attribute with this scheme: 然后使用此方案的Authorize属性:

[Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]

Another option is using UseWhen to seperate admin and default authentication: 另一种选择是使用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
          });
      });

And then just use Authorize attribute. 然后只使用Authorize属性。

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

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