Introduction
Creating a user account in a web application is more than saving values from a form into a database. Registration must validate user input, process passwords securely, prevent duplicate usernames or email addresses, and report failures without exposing unnecessary information. During login, the submitted password must be verified, account status must be checked, and a secure authentication cookie must be created after successful authentication.
In this lesson, we will implement three essential flows with ASP.NET Core Identity: user registration, user login and user logout. The examples use an MVC Controller approach. The same UserManager and SignInManager services can also be used from Razor Pages or an application-specific API layer.
Because Identity was integrated in the previous lesson, this lesson assumes that ApplicationUser, ApplicationDbContext and the Identity services are already available.
1. The parts of an account flow
User registration
A typical registration process includes the following steps:
- Collect an email address, username and password.
- Run model validation.
- Check whether the email address or username is already in use.
- Create the user through
UserManager.CreateAsync. - Inspect the result returned by Identity.
- Redirect to login or start an email-confirmation process after successful registration.
Passwords must never be written directly to the database. UserManager uses the configured password-hashing component and stores a password hash instead of the original value. Application code should never store, log or return a user's plain-text password.
User login
During login, the application can find a user by username or email address. Once the user is found, the password is verified with SignInManager.PasswordSignInAsync. If authentication succeeds, Identity creates an authentication cookie containing the user's identity information. The cookie is then read on subsequent requests to identify the signed-in user.
User logout
Logout calls SignInManager.SignOutAsync. This ends the current authentication session and causes the related cookie to be removed or invalidated. A logout endpoint should normally use an HTTP POST request and anti-forgery protection because it changes authentication state.
2. Creating ViewModels
Using dedicated ViewModel classes instead of binding forms directly to entity classes is safer. A ViewModel accepts only the fields that the user is allowed to submit and prevents the database model from being accidentally exposed or overposted.
using System.ComponentModel.DataAnnotations;
public sealed class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; } = string.Empty;
[Required]
[StringLength(50, MinimumLength = 3)]
[Display(Name = "Username")]
public string UserName { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
public string Password { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
[Compare(nameof(Password))]
public string ConfirmPassword { get; set; } = string.Empty;
}
public sealed class LoginViewModel
{
[Required]
[Display(Name = "Username or email")]
public string UserNameOrEmail { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
public string Password { get; set; } = string.Empty;
[Display(Name = "Remember me")]
public bool RememberMe { get; set; }
}Attributes such as Required, EmailAddress and Compare provide basic input validation. They do not replace Identity's password policy. Requirements such as minimum password length and character categories are configured separately through Identity options.
3. Configuring Identity user and password options
Identity applies password rules by default, but security requirements should be configured explicitly for the application. Instead of relying only on complex character rules that users may try to bypass, consider a layered approach that includes sufficiently long passwords, protection against common passwords and, where appropriate, multi-factor authentication.
builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.User.RequireUniqueEmail = true;
options.Password.RequiredLength = 12;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.AllowedForNewUsers = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();When RequireUniqueEmail is enabled, two accounts cannot use the same email address. Lockout settings provide an additional defense against repeated failed login attempts. These settings do not completely solve brute-force attacks; rate limiting and further protections will be discussed later in the course.
4. Implementing registration
The controller receives UserManager<ApplicationUser> through dependency injection. If the submitted model is invalid, the form is displayed again. If validation succeeds, a new user object is created and the password is passed only to Identity through CreateAsync.
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
return View(model);
var user = new ApplicationUser
{
UserName = model.UserName.Trim(),
Email = model.Email.Trim().ToLowerInvariant()
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
return RedirectToAction(nameof(Login));
foreach (var error in result.Errors)
ModelState.AddModelError(string.Empty, error.Description);
return View(model);
}
}The errors in result.Errors can describe password-policy violations, duplicate usernames or duplicate email addresses. Show controlled validation messages rather than raw exception details. In production, also consider whether a particular message reveals too much about whether an account exists.
5. Logging in and creating the authentication cookie
For login, the application first searches for a user by username or email. When no user is found, a generic error message is preferable because it makes account enumeration more difficult.
[HttpGet]
public IActionResult Login(string? returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(
LoginViewModel model,
string? returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid)
return View(model);
var loginValue = model.UserNameOrEmail.Trim();
ApplicationUser? user;
if (loginValue.Contains('@'))
user = await _userManager.FindByEmailAsync(loginValue);
else
user = await _userManager.FindByNameAsync(loginValue);
if (user is null)
{
ModelState.AddModelError(string.Empty,
"Invalid login information.");
return View(model);
}
var result = await _signInManager.PasswordSignInAsync(
user,
model.Password,
model.RememberMe,
lockoutOnFailure: true);
if (result.Succeeded)
{
if (!string.IsNullOrWhiteSpace(returnUrl) &&
Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
if (result.IsLockedOut)
{
ModelState.AddModelError(string.Empty,
"The account is temporarily locked.");
}
else if (result.IsNotAllowed)
{
ModelState.AddModelError(string.Empty,
"This account is not currently allowed to sign in.");
}
else
{
ModelState.AddModelError(string.Empty,
"Invalid login information.");
}
return View(model);
}Setting lockoutOnFailure: true causes failed password attempts to contribute to the lockout counter. Whenever returnUrl is used, validate it with Url.IsLocalUrl. Without this check, an attacker could abuse the login flow for an open-redirect attack that sends users to an external address after authentication.
6. Implementing logout
Logout is best represented by a POST action. The user interface can send a request through a form, although the form markup is outside the scope of this lesson. The endpoint can be implemented as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}Using GET for logout can allow browsers, crawlers or prefetching mechanisms to invoke the URL unintentionally. Use POST and anti-forgery protection for operations that change authentication state.
7. Cookie security settings
The behavior of the Identity cookie directly affects session security. Use HttpOnly to prevent client-side JavaScript from reading the cookie, SecurePolicy to require HTTPS, and an appropriate SameSite value to reduce cross-site request risks.
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "CourseApp.Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});SameSite=Lax is a reasonable starting point for many traditional web applications. If external identity providers or special cross-site scenarios are required, evaluate SameSite=None together with the required Secure setting. Production applications should require HTTPS and ensure that Data Protection keys persist across restarts and deployments.
8. Common mistakes
- Hashing passwords manually: Use Identity's
PasswordHasherandUserManagermechanisms. - Binding forms directly to entities: Use ViewModels to prevent accidental updates to fields that users should not control.
- Returning detailed login errors: Separating “email not found” from “password incorrect” can help account enumeration.
- Failing to validate return URLs: Redirect only to local URLs.
- Using GET for logout: Use POST with anti-forgery protection for state-changing operations.
- Treating the cookie as a sensitive-data store: Do not place unnecessary personal or secret information in the cookie.
- Copying development settings to production: Review HTTPS, persistent Data Protection keys and cookie expiration settings before deployment.
9. Practice exercise
In the existing Identity project, create RegisterViewModel, LoginViewModel and AccountController. First, try to register with an invalid email address and a short password. Then create a valid user and attempt to register a second account with the same email address. Submit several incorrect passwords and observe the lockout behavior. After a successful login, inspect the authentication cookie in the browser developer tools and verify its HttpOnly, Secure and SameSite properties. Finally, call the logout action and confirm that a protected page redirects to the login page afterward.
Conclusion
This lesson implemented the three fundamental stages of the ASP.NET Core Identity user lifecycle. ViewModel validation and Identity password policies worked together during registration. During login, UserManager located the user, SignInManager verified the password, and a secure authentication cookie was created. Failed-login lockout and generic error messages were applied. Logout ended the session and was protected with anti-forgery validation.
In the next stage, we will add roles and claims to this foundation and control who can access specific resources. The focus will move from “has the user signed in?” to the more useful question: “which operations is this user allowed to perform?”
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-10.0
- 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/cookie?view=aspnetcore-10.0