LESSON 12 OF 20

12. User Authentication and Administrator Login

Build user registration, login, logout, password policies, roles, and secure administrator access with ASP.NET Core Identity.

45 dk 33

Introduction

Our content management application now needs a secure way for users to register, sign in, and sign out. The administration area must also be protected so that it is available only to authorized administrators, not to every registered user. In this lesson, we will implement that flow with ASP.NET Core Identity.

ASP.NET Core Identity is a built-in system for managing users, passwords, roles, claims, tokens, and authentication cookies. It does not store passwords as plain text. In MVC applications, much of the default Identity interface is provided as Razor Pages under the Areas/Identity/Pages area.

By the end of this lesson, visitors will be able to register and sign in, while only users in the Administrator role will be allowed to open the administration panel.

1. Preparing the project for Identity

Identity must use the SQL Server database that already exists in our project. We will assume that the ApplicationDbContext created in earlier lessons inherits from IdentityDbContext.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Article> Articles => Set<Article>();
}

If the project template does not already include the required packages, add them with:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Identity.UI

2. Configuring Identity services

Add Identity to Program.cs after registering the database context. Because the application will use roles, the AddRoles<IdentityRole>() call is essential.

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("DefaultConnection was not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
    options.Password.RequiredLength = 10;
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredUniqueChars = 4;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();

app.Run();

UseAuthentication reads the authentication cookie and builds the current user identity. UseAuthorization evaluates whether that identity can access a resource. MapRazorPages exposes the registration, login, logout, and account-management pages supplied by Identity.

3. Creating the database migration

Identity creates tables such as AspNetUsers, AspNetRoles, and AspNetUserRoles. Create and apply a migration after changing the context:

dotnet ef migrations add AddIdentityTables
dotnet ef database update

For production deployments, apply migrations as a controlled deployment step rather than automatically changing the database every time the application starts.

4. Registration, login, and logout

The default Identity UI provides these addresses:

  • /Identity/Account/Register: Create a user account
  • /Identity/Account/Login: Sign in
  • /Identity/Account/Logout: Sign out
  • /Identity/Account/Manage: Manage account settings

You may not see these pages as physical files in the project. That is expected: the default UI is supplied through a Razor Class Library. Scaffold only the pages that you need to customize, such as Register or Login.

To show authentication links in the shared layout, add the login partial:

<partial name="_LoginPartial" />

Depending on the selected project template, the partial may be supplied by Identity UI or generated during scaffolding. When customizing scaffolded pages, preserve their validation attributes and security-related behavior.

5. Password policy

A password policy is an important part of protecting administrator accounts. In this lesson, passwords must be at least 10 characters and contain uppercase, lowercase, numeric, non-alphanumeric, and sufficiently unique characters.

A policy should not be made unnecessarily difficult. Excessive complexity rules can encourage predictable patterns. In a production application, also consider long unique passwords, password managers, account lockout settings, email confirmation, and multi-factor authentication.

If Identity pages have been scaffolded, inspect any StringLength attributes in Register.cshtml.cs or ResetPassword.cshtml.cs. A UI-level validation rule that conflicts with the configured PasswordOptions can produce confusing results for users.

6. Creating the administrator role and account

Being able to sign in does not automatically grant administrator permissions. We must create the role and then assign a controlled user to it. The following seeding service creates the role and administrator account when the application starts.

using Microsoft.AspNetCore.Identity;

public static class IdentitySeed
{
    public static async Task SeedAsync(IServiceProvider services,
        IConfiguration configuration)
    {
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        var userManager = services.GetRequiredService<UserManager<IdentityUser>>();

        const string roleName = "Administrator";
        if (!await roleManager.RoleExistsAsync(roleName))
        {
            var roleResult = await roleManager.CreateAsync(new IdentityRole(roleName));
            if (!roleResult.Succeeded)
            {
                throw new InvalidOperationException(
                    string.Join("; ", roleResult.Errors.Select(e => e.Description)));
            }
        }

        var email = configuration["AdminSeed:Email"];
        var password = configuration["AdminSeed:Password"];

        if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
        {
            throw new InvalidOperationException("Administrator settings are missing.");
        }

        var user = await userManager.FindByEmailAsync(email);
        if (user is null)
        {
            user = new IdentityUser
            {
                UserName = email,
                Email = email,
                EmailConfirmed = true
            };

            var userResult = await userManager.CreateAsync(user, password);
            if (!userResult.Succeeded)
            {
                throw new InvalidOperationException(
                    string.Join("; ", userResult.Errors.Select(e => e.Description)));
            }
        }

        if (!await userManager.IsInRoleAsync(user, roleName))
        {
            await userManager.AddToRoleAsync(user, roleName);
        }
    }
}

Run the seed operation before app.Run() by creating a service scope:

using (var scope = app.Services.CreateScope())
{
    await IdentitySeed.SeedAsync(
        scope.ServiceProvider,
        scope.ServiceProvider.GetRequiredService<IConfiguration>());
}

app.Run();

Never place the administrator password in source code or commit it to appsettings.json. Use user-secrets during development and environment variables or a managed secret store in production. For example:

dotnet user-secrets set "AdminSeed:Email" "admin@example.com"
dotnet user-secrets set "AdminSeed:Password" "Strong-and-unique-password!2026"

For a real system, plan to require a password change after initial provisioning and enable multi-factor authentication for administrator accounts.

7. Protecting the administration panel

Restrict the administration controller to members of the Administrator role:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Articles()
    {
        return View();
    }
}

An unauthenticated user is redirected to the login page. An authenticated user without the required role is redirected to the access-denied page. Configure those paths explicitly if desired:

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
});

Use [Authorize] when any authenticated user may access an action. Use [Authorize(Roles = "Administrator")] when access must be limited to a specific role.

8. Showing the administrator link in the UI

Showing the administration link only to authorized users improves navigation, but it is not a security boundary. The controller must remain protected with Authorize.

@if (User.Identity?.IsAuthenticated == true &&
    User.IsInRole("Administrator"))
{
    <a asp-controller="Admin" asp-action="Index">
        Administration Panel
    </a>
}

If User.IsInRole is sufficient, avoid injecting an unnecessary UserManager into the view. Keep authorization rules on the server even when the navigation hides unauthorized links.

Common mistakes

  • Forgetting AddRoles: Role records may exist in the database, but role services are unavailable unless they are registered.
  • Forgetting MapRazorPages: MVC routes may work while /Identity/Account/Login returns a routing error.
  • Using the wrong middleware order: Authentication and authorization must run before endpoint execution.
  • Considering a hidden menu secure: A user can still type a protected URL directly.
  • Committing the administrator password: Secrets must not appear in source code, migration files, or logs.
  • Assigning Administrator to every user: Role assignment must be controlled and auditable.

Practice exercise

  1. Create and apply the Identity migration to the SQL Server database.
  2. Configure an administrator email address and strong password through user-secrets.
  3. Run the seed code and verify that the Administrator role exists.
  4. Register a normal user at /Identity/Account/Register.
  5. Try to open /Admin as the normal user and verify that access is denied.
  6. Sign in as the administrator and verify that the panel opens.
  7. Confirm that the administration link appears only for the administrator account.

Conclusion

In this lesson, we connected ASP.NET Core Identity to our MVC application, configured a password policy, enabled registration, login, and logout, and created an administrator through role-based provisioning. The administration panel is now protected at the server level, not merely hidden in the user interface.

In the next lessons, we can associate authenticated users with content operations so that the application records who created or modified each article.

Sources