How to fix LoginPath not working in ASP.NET Core

By FoxLearn 6/10/2024 8:05:12 AM   1.03K
How to solve 'LoginPath not working in ASP.NET Core'.

If your LoginPath is not working in ASP.NET Core, there could be a few reasons why it's not functioning as expected. Here's a step-by-step approach to troubleshoot and potentially solve the issue:

By default, if you don't configure it's automatically redirect to "/Account/Login?RedirectUrl=%2F"

Verify that you have correctly configured the LoginPath property in your authentication middleware setup.

Opening your Startup class, then add a configuration as shown below.

services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = new PathString("/Identity/Account/Login");
                options.ReturnUrlParameter = "RedirectUrl";
                options.LogoutPath = new PathString("/Identity/Account/Lockout");
                options.AccessDeniedPath = new PathString("/Identity/Account/AccessDenied");
                options.ExpireTimeSpan = TimeSpan.FromDays(1);
            });

Make sure that the LoginPath is set to the correct path where your login page is located.

If you've updated from beta 5 to beta 8, you can't set the custom login path in cookie authentication options.

services.AddCookieAuthentication(config =>
{
     config.LoginPath = new PathString("Auth/Login");
});

You will still gets redirected to the default '/Account/Login'. To solve the problem, you can do this a bit differently.

services.Configure<IdentityOptions>(options=>
{
    options.Cookies.ApplicationCookie.LoginPath = new PathString("/Auth/Login");
});

Ensure that the route specified in the LoginPath matches the route configuration in your application. If your login page is located at /Account/Login, make sure that you have defined a corresponding route for it.

Instead of use services.AddAuthentication().AddCookie

services.AddAuthentication().AddCookie(options =>
            {
    options.LoginPath = "/Identity/Account/Login";
    options.ExpireTimeSpan = TimeSpan.FromDays(1);
});