I'm working on an ASP.NET Core 8 MVC project; when someone tries to manually type in the URL to access the page, it should redirect them to a login page if not logged in, however, I get this error of page not found. To my understanding to redirect it is by doing this:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opts => {
opts.LoginPath = "/Home/Login";
// I don't know if passing nothing in the cookie name is affecting it or not
opts.Cookie.Name = "";
opts.ExpireTimeSpan = TimeSpan.FromMinutes(30);
opts.AccessDeniedPath = "/Home/Unauthorized";
});
But instead, I get this error
This localhost page can’t be found No webpage was found for the web address: http://localhost:5278/Identity/Account/Login?ReturnUrl=%2FAdmin%2FNewClient
HTTP ERROR 404
Why is it pointing still at this URL http://localhost:5278/Identity/Account/Login?ReturnUrl=%2FAdmin%2FNewClient
instead of opts.LoginPath
?
To clarify I'm using .NET 8
Try this code:
builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
// Customize cookie settings for Identity
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Home/Login"; // Redirect to your custom login page
options.AccessDeniedPath = "/Home/Unauthorized";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
});
This will help you to override the login path and you do not need to use AddAuthentication().AddCookie() if you're using AddDefaultIdentity(), as it already handles the cookie authentication.
ConfigureApplicationCookie must be called after calling AddIdentity or AddDefaultIdentity.
Here is the document you could refer: