3

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

is there another way ?
If you mean another way without authentication middleware, i would say "no" for authentication purpose. But for branching(admin, default etc.) there may be another way such as MapWhen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.