Problem with Authentication

Hello, I followed the examples in these two pages to create a very simple authentication mechanism.

The authentication works fine when I add

Context.Authorize();

to the Init() method of each ViewModel independently
However, when I only add it to the MasterPage ViewModel in order to require authentication over all my pages I instead get a very strange behavior, where I am getting a page loading while redirects are added to the url resulting in something like this:

image

going on for many lines, but you get the point.
Any ideas as to why that might be? I’ve never worked with Authentication before so any ideas are welcome!

At first glance, it seems like you are also calling Context.Authorize() on the login page, getting you into a redirect loop.

I also looked for something like that at first, but on my Login.dothtml I only have this:

public override Task Init()
{
   
    return base.Init();
}
 services.AddAuthentication(sharedOptions =>
 {
     sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
 })
     .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
     {
         options.Events = new CookieAuthenticationEvents
         {
             OnRedirectToReturnUrl = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
             OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403),
             OnRedirectToLogin = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri),
             OnRedirectToLogout = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri)
         };
         options.LoginPath = "/login";
     });

this is my Authentication service on Startup.cs copied directly from the documentation.

and this is the way I add my Login page in DotvvmStartup.cs in case this helps at all

config.RouteTable.Add("Login", "login", "Views/Login.dothtml");

I see, but I suppose that the loop will still happen, if the LoginViewModel inherits from the base class where you call Context.Authorize()

I see, that does make sense. However, according to the documentation:

If you want the same permission check for all pages, you can place the Authorize method call to the master page viewmodel. If you override the Init method in page viewmodels, make sure to properly call await base.Init(context); so the check is applied.

What other steps should I take to state that the /login url does not need to be authenticated so to resolve this problem?

You have to avoid calling Authorize in the specific case. For instance, using an if (Context.Route.Name != "YourLoginPage") condition or placing the Authorize call into a virtual method which you override to be empty in the LoginViewModel