Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom authorization attributes in ASP.NET Core

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 ?

like image 741
Mo3in Avatar asked Mar 08 '26 21:03

Mo3in


1 Answers

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.

like image 53
adem caglin Avatar answered Mar 11 '26 10:03

adem caglin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!