Custom authorization attributes in ASP.NET Core

Mo3in picture Mo3in · Jul 8, 2016 · Viewed 7.1k times · Source

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 ?

Answer

adem caglin picture adem caglin · Jul 8, 2016

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.