[![Message error]] [1]: https://i.sstatic.net/ciKCK.png
My point is if someone go to Authorize page without login, It will be redirected to the login page.
This is my code (.NET Core 3.1):
My Controller
[Authorize]
public IActionResult Username()
{
var lstUsername = _dbContext.MT_USERNAME.ToList();
return View(lstUsername);
}
My Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GPServiceDbContext>(options =>
{
options.UseSqlServer(xxx);
});
services.AddControllersWithViews();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(1);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseStatusCodePages(context =>
{
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
response.Redirect("/Login/Login");
return Task.CompletedTask;
});
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Login}/{id?}");
});
}
In my case there was just a simple error on authentication options parameter
options.DefaultAuthenticateScheme
instead of this:
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With