Home > Net >  ASP.NET CORE MVC identity users and roles doesn't work
ASP.NET CORE MVC identity users and roles doesn't work

Time:11-03

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:

  1. Decorate each endpoint you want to have protected with [Authorize]. This can get very repetetive in larger codebases.
  2. 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:

  • Related