I have a ASP.NET CORE MVC 3.1 application with Identity enabled:
services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
The DB Context inherits from identity:
ApplicationDbContext : IdentityDbContext
Startup configuration:
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();
});
However, it doesn't enforce authentication when navigating through the application. If however, I use services.AddDefaultIdentity, it works but I lose functionality of accessing RolManager for getting the roles of authenticated user.
Can you please advise on what do I need to do to enforce the authentication?
CodePudding user response:
You have 2 possibilities:
- Decorate each endpoint you want to have protected with
[Authorize]
. This can get very repetetive in larger codebases. - Globally require Authorization on your endpoints:
app.UseEndpoints(endpoints =>
{
//or | and MapControllersWithViews()
endpoints.MapControllers().RequireAuthorization();
endpoints.MapRazorPages().RequireAuthorization();
});
Be aware, that this will also protect your Login endpoints as well, so you have to exclude them, by decorating them with [AllowAnonymous]
.
Details: