简体   繁体   中英

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

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?

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");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM