Password checking validates a candidate password against ASP.NET Core Identity policy rules during user creation. Failed checks return IdentityError objects through IdentityResult and appear in the form’s validation summary. section 38.3.3
Configure the policy through IdentityOptions.Password:
- RequiredLength sets the minimum password length. section 38.3.3
- RequireNonAlphanumeric requires a non-letter, non-digit character. section 38.3.3
- RequireLowercase, RequireUppercase, and RequireDigit enforce lowercase, uppercase, and numeric characters. section 38.3.3
Testing a policy
Open /Users/Create, enter Alice with password secret, and submit. The default policy rejects it. After requiring only six characters and disabling the other constraints, the same password is accepted and the user is created. section 38.3.3
Listing 38.13 Configuring validation in the Program.cs file in the Advanced project
using Microsoft.EntityFrameworkCore;
using Advanced.Models;
using Microsoft.AspNetCore.Identity;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddDbContext<DataContext>(opts => {
opts.UseSqlServer(
builder.Configuration["ConnectionStrings:PeopleConnection"]);
opts.EnableSensitiveDataLogging(true);
});
builder.Services.AddSingleton<Advanced.Services.ToggleService>();
builder.Services.AddDbContext<IdentityContext>(opts =>
opts.UseSqlServer(builder.Configuration[
"ConnectionStrings:IdentityConnection"]));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityContext>();
builder.Services.Configure<IdentityOptions>(opts => {
opts.Password.RequiredLength = 6;
opts.Password.RequireNonAlphanumeric = false;
opts.Password.RequireLowercase = false;
opts.Password.RequireUppercase = false;
opts.Password.RequireDigit = false;
});
var app = builder.Build();
app.UseStaticFiles();
app.MapControllers();
app.MapControllerRoute("controllers",
"controllers/{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.UseBlazorFrameworkFiles("/webassembly");
app.MapFallbackToFile("/webassembly/{*path:nonfile}",
"/webassembly/index.html");
var context = app.Services.CreateScope().ServiceProvider
.GetRequiredService<DataContext>();
SeedData.SeedDatabase(context);
app.Run();
Inspect the Program.cs configuration that changes IdentityOptions.Password validation behavior. section 38.3.3
