How do I set two different login paths for authorization challenge? (ASP.NET Core Razor Pages)

Viewed 424

So this is how I set login path which redirects to login page for authorization challenge, right?

builder.Services.Configure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options =>
{
    options.LoginPath = "/Account/Login";

});

But what if I have two login pages - one for admin and one for regular users? How do I register two different login pages for two different parts of the web?

1 Answers

You can overwrite the OnRedirectToLogin event on the options :

builder.services.Configure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options =>
{
     options.LoginPath = "/Account/Login";
     options.Events.OnRedirectToLogin = context =>
     {
          if (IsAdminContext(context))
          {
             var redirectPath = new Uri(context.RedirectUri);
             context.Response.Redirect("/Account/AdminLogin" + redirectPath.Query);
          }
          else
          {
             context.Response.Redirect(context.RedirectUri);
          }
           return Task.CompletedTask;
      };
 });

And Create Helper Method Like This :

 private static bool IsAdminContext(RedirectContext<CookieAuthenticationOptions> context)
 {
    return context.Request.Path.StartsWithSegments("/admin");
 }
Related