Introduction
A user being able to sign in successfully does not mean that account management is complete. Users need to create strong passwords, change existing passwords safely, recover access when they forget a password and receive protection against suspicious sign-in attempts.
In this lesson, we will extend the ASP.NET Core Identity infrastructure introduced in the previous lesson into a more secure account-management solution. We will configure password rules, implement password changes and resets with UserManager, enable automatic lockout after repeated failures and review security considerations for sensitive account operations.
The examples use ASP.NET Core MVC, Entity Framework Core and IdentityUser. The same services can be used in Razor Pages or Web API applications with similar application-flow decisions.
Configuring Identity password policies
ASP.NET Core Identity does not store passwords as plain text. When a user is created, Identity processes the password with its configured password hasher and stores a password hash in the database. Defining the password policy explicitly is therefore an important part of the application design.
The password policy can be configured with Configure<IdentityOptions> after registering Identity:
using Microsoft.AspNetCore.Identity;
builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 12;
options.Password.RequiredUniqueChars = 4;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.User.RequireUniqueEmail = true;
});RequiredLength specifies the minimum length, while RequiredUniqueChars specifies how many distinct characters are required. Uppercase, lowercase, digit and non-alphanumeric requirements can also be enabled independently.
Character diversity alone is not enough. Encourage long passphrases, block commonly used or compromised passwords, add multifactor authentication and limit password attempts. An excessively complicated policy can cause users to reuse passwords or store them in unsafe places, so the policy should be appropriate for the application risk.
Account lockout and failed-login limits
To reduce password-guessing attacks, an account can be temporarily locked after a configured number of failed sign-in attempts. Identity supports this behavior through LockoutOptions:
builder.Services.Configure<IdentityOptions>(options =>
{
options.Lockout.AllowedForNewUsers = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});MaxFailedAccessAttempts is the failure threshold. When the threshold is reached, the account is locked for the period specified by DefaultLockoutTimeSpan. A successful sign-in resets the failed-access count.
The login operation must also enable lockout on failure. This is done by passing true to the lockoutOnFailure parameter of PasswordSignInAsync:
var result = await _signInManager.PasswordSignInAsync(
model.Email,
model.Password,
model.RememberMe,
lockoutOnFailure: true);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
if (result.IsLockedOut)
{
ModelState.AddModelError(string.Empty,
"Your account has been temporarily locked because of too many failed attempts.");
return View(model);
}
ModelState.AddModelError(string.Empty,
"The email address or password is invalid.");
return View(model);Using a similar message for a missing user and an incorrect password helps avoid revealing whether an account exists. Distinct messages such as “user not found” and “incorrect password” can make account-enumeration attacks easier.
Changing a password
An authenticated user who knows the current password can change it. The appropriate API for this scenario is UserManager.ChangePasswordAsync. It validates the current password, applies the configured password policy and stores the new password hash when the operation succeeds.
First, define a view model:
public sealed class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
public string CurrentPassword { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
public string NewPassword { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
[Compare(nameof(NewPassword))]
public string ConfirmPassword { get; set; } = string.Empty;
}Then create an action that is accessible only to authenticated users:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.GetUserAsync(User);
if (user is null)
{
return Challenge();
}
var result = await _userManager.ChangePasswordAsync(
user,
model.CurrentPassword,
model.NewPassword);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(model);
}
await _signInManager.RefreshSignInAsync(user);
return RedirectToAction(nameof(ChangePasswordSuccess));
}RefreshSignInAsync refreshes the current sign-in using the user's current information. This is useful when security-related identity data or the security stamp changes and the session should remain synchronized with the account state.
Keep GET and POST actions separate, use antiforgery validation on the POST operation and obtain the user from the current ClaimsPrincipal rather than trusting a user ID supplied by a form or URL.
Token-based password reset
Password reset is used when a user no longer knows the current password. In a secure flow, the user submits an email address, the application generates a time-sensitive Identity token and sends a link through a verified email channel.
The first action should start the process without revealing whether the email address exists:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user is not null &&
await _userManager.IsEmailConfirmedAsync(user))
{
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
var encodedToken = WebEncoders.Base64UrlEncode(
Encoding.UTF8.GetBytes(token));
var callbackUrl = Url.Action(
"ResetPassword",
"Account",
new { email = user.Email, code = encodedToken },
protocol: Request.Scheme);
await _emailSender.SendPasswordResetLinkAsync(
user.Email!, callbackUrl!);
}
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}_emailSender is an application-specific abstraction. Writing the link to a controlled development output can be useful during local testing, but production systems must not place reset tokens in logs, exception messages or analytics systems.
The token from the reset link is decoded and validated with ResetPasswordAsync:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user is null)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
string token;
try
{
token = Encoding.UTF8.GetString(
WebEncoders.Base64UrlDecode(model.Code));
}
catch (FormatException)
{
ModelState.AddModelError(string.Empty,
"The password reset link is invalid or malformed.");
return View(model);
}
var result = await _userManager.ResetPasswordAsync(
user, token, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(model);
}Identity validates the token and determines whether it can be used. Token lifetime, Data Protection keys and the user's security stamp can affect reset-link behavior. In production, store Data Protection keys in a secure, persistent location. Otherwise, application restarts or deployment changes may invalidate tokens unexpectedly.
Security for sensitive account operations
- Use HTTPS: Passwords, reset tokens and authentication cookies must be transmitted only over encrypted connections.
- Enable CSRF protection: Cookie-authenticated POST operations such as password changes and profile updates should use antiforgery validation.
- Use short-lived tokens: Password-reset links should expire and should be designed to be single-use where appropriate.
- Avoid account enumeration: Return a generic response such as “If the address is registered, instructions have been sent.”
- Apply rate limiting: Sign-in, password reset and email-sending operations are common abuse targets.
- Keep audit events: Record password changes, lockouts and reset events without storing passwords or reset tokens.
- Do not hash passwords yourself: Use Identity's
PasswordHasherandUserManagerworkflows.
Common mistakes
- Leaving
lockoutOnFailuredisabled: Lockout options alone may not be enough if the login operation does not enable failed-attempt tracking. - Failing to encode the token: Identity tokens can contain special characters. Base64 URL encoding reduces the risk of broken links.
- Persisting reset tokens as plain text: The token usually does not need to be stored permanently. If persistence is required, protect or hash stored values appropriately.
- Using security questions: Easily guessed answers do not provide sufficient protection for password recovery.
- Ignoring existing sessions after a password change: Depending on the threat model, rotate the security stamp and invalidate other sessions when necessary.
Practice exercise
Add the following features to the existing Identity project:
- Configure a policy requiring at least 12 characters, one digit and one special character.
- Lock an account for 15 minutes after five failed sign-in attempts.
- Create a password-change page for authenticated users.
- Design an email sender behind an interface for the forgot-password flow.
- In development, expose the reset link only through a controlled test output; never log the token in production.
- Verify that existing and non-existing email addresses receive the same public response.
- Submit an incorrect password more than five times and verify the lockout behavior.
Conclusion
Secure account management is more than enforcing a complex password rule. Password changes, password resets, email confirmation, failed-login limits, temporary lockout, antiforgery protection, HTTPS and safe logging must be considered together.
ASP.NET Core Identity provides a strong foundation through UserManager, SignInManager, token providers and IdentityOptions. In the next stage, we will connect these user accounts to more detailed authorization rules using roles and claims.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1?view=aspnetcore-10.0