I have an ASP.Net core 3.1 application with Identity and 2 pages: Index and Private (authorization required). When I browse to the Private page directly, I would expect the application to redirect me to the login page. Yet instead the broswer shows {"message":"Unauthorized"}. Where is that message coming from and why is it not redirecting to login?
(Navigating to login /Identity/Account/Login directly DOES show the login page)
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<BackendUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseStatusCodePages();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult Private()
{
return View();
}
}
I could not reproduce your problem. You might have another problem with your project. You are using some middleware for example.
Anyway, try to logout and login again or clear the browser cookies, because the login process adds cookies to the browser to identify authentication. This will renew any broken cookies and probably will fix the authorization problem.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments