Custom authorization attributes in ASP.NET Core

喜夏-厌秋 提交于 2019-12-09 19:36:52

问题


i'm working on asp.net core and i don't understand some things. for example in mvc.net 5 we can filter and authorize action with create class from AuthorizeAttribute and set attribute to actions like this:

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 ?


回答1:


You can use authentication middleware and Authorize attirbute to redirect login page. For your case also using AuthenticationScheme seems reasonable.

First use(i assume you want use cookie middleware) cookie authentication middleware:

        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 Authorizeattribute with this scheme:

[Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]

Another option is using UseWhen to seperate admin and default authentication:

      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.



来源:https://stackoverflow.com/questions/38264791/custom-authorization-attributes-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!