ASP.NET Core  

Using ASP.NET Core Identity for Authentication Best Practices

Authentication is the foundation of application security. In ASP.NET Core, the Identity framework provides a powerful membership system that handles user registration, login, password hashing, roles, claims, and more. However, simply enabling Identity is not enough—you must follow best practices to ensure your application remains secure, scalable, and maintainable.

In this article, we’ll explore ASP.NET Core Identity, how to configure it, and the best practices to follow when using it in production applications.

What is ASP.NET Core Identity?

ASP.NET Core Identity is a membership system that provides:

  • User registration and login

  • Role-based and claims-based authorization

  • Secure password storage with hashing and salting

  • Two-Factor Authentication (2FA)

  • External logins (Google, Facebook, Microsoft, etc.)

  • Account lockout, email confirmation, password reset

Setting Up ASP.NET Core Identity

Step 1. Install Required Packages

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 2. Configure Identity in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add EF Core with SQL Server
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Add Identity
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    options.Password.RequiredLength = 8;
    options.Password.RequireUppercase = true;
    options.Password.RequireDigit = true;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute();
app.Run();

Step 3. Create Application User Class

public class ApplicationUser : IdentityUser
{
    // Add custom properties if needed
    public string FullName { get; set; }
}

Step 4. Apply Migrations

dotnet ef migrations add InitialIdentity
dotnet ef database update

Best Practices for Using ASP.NET Core Identity

1. Secure Password Policies

  • Enforce strong password requirements (length, uppercase, numbers, special characters).

  • Example

    options.Password.RequiredLength = 12;
    options.Password.RequireNonAlphanumeric = true;
    

2. Use Account Lockout

  • Prevent brute force attacks by locking accounts after multiple failed attempts.

    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
    

3. Enable Email Confirmation

  • Require users to confirm their email before login.

    options.SignIn.RequireConfirmedEmail = true;
    

4. Two-Factor Authentication (2FA)

  • Add an extra layer of protection with SMS, authenticator apps, or email-based 2FA.

  • Example

    var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email");
    

5. Protect Sensitive Routes

  • Require authenticated users with [Authorize].

  • Example

    [Authorize(Roles = "Admin")]
    public IActionResult Dashboard()
    {
        return View();
    }
    

6. Use Claims for Fine-Grained Authorization

  • Roles are useful, but claims give more flexibility.

  • Example

    var claim = new Claim("Department", "Finance");
    await _userManager.AddClaimAsync(user, claim);
    

7. Secure Cookie Settings

  • Identity uses cookies by default. Harden them:

    builder.Services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    });
    

8. Use External Login Providers Securely

  • Integrate OAuth2 providers (Google, Microsoft, Facebook).

  • Always validate scopes and limit permissions to only what’s necessary.

9. Regularly Rotate Security Keys

  • Protect JWTs and cookies by rotating keys regularly.

10. Use Data Protection API for Token Security

  • ASP.NET Core Identity uses Data Protection under the hood. Store keys securely (Azure Key Vault, AWS KMS, etc.).

Sample: Secure Login Endpoint

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(
            model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);

        if (result.Succeeded)
            return RedirectToAction("Index", "Home");

        if (result.IsLockedOut)
            return View("Lockout");

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
    }
    return View(model);
}

Conclusion

ASP.NET Core Identity provides a secure and flexible authentication system out of the box. By following best practices like strong password policies, 2FA, email confirmation, claims-based authorization, and secure cookie settings, you can significantly improve the security posture of your application.