skip to content

In ASP.NET Core Identity, what do UserManager<TUser> and SignInManager<TUser> each do when a user registers and then signs in?

level: juniorimportance: must knowfreq 68%

answer

  1. stored users versus signed-in sessions
  2. CreateAsync returns an IdentityResult
  3. PasswordSignInAsync returns a SignInResult
  4. IsLockedOut, IsNotAllowed, RequiresTwoFactor
  5. the Identity.Application cookie

basics

~20 s

UserManager manages stored users through a store: creating them, hashing and checking passwords, confirming e-mail, roles and lockout counts. SignInManager turns a verified user into a signed-in session by running the sign-in checks and issuing the Identity.Application cookie.

solid answer

~40 s

`UserManager<TUser>` is the API over the user store: `CreateAsync(user, password)` validates the user and password against the configured rules, hashes the password with `IPasswordHasher<TUser>` and saves the user, returning an `IdentityResult` whose `Errors` carry codes such as `PasswordTooShort` or `DuplicateUserName`. It also confirms e-mail, manages roles and claims and counts failed attempts. `SignInManager<TUser>` handles the session: `PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure)` first checks whether the user may sign in (confirmed account, not locked out), then the password, then two-factor, and on success signs in with the `Identity.Application` cookie scheme. It returns a `SignInResult` with `Succeeded`, `IsLockedOut`, `IsNotAllowed` or `RequiresTwoFactor`. Both are scoped services resolved per request, and both sit on a store such as the EF Core one from `AddEntityFrameworkStores`.

code

csharp · 24 lines
csharp
app.MapPost("/account/register", async (SignUp form, UserManager<IdentityUser> users) =>
{
    var user = new IdentityUser { UserName = form.Email, Email = form.Email };
    var created = await users.CreateAsync(user, form.Password);
    return created.Succeeded
        ? Results.Ok()
        : Results.BadRequest(created.Errors.Select(e => e.Code));
});

app.MapPost("/account/login", async (SignInForm form, SignInManager<IdentityUser> signIn) =>
{
    var result = await signIn.PasswordSignInAsync(form.Email, form.Password,
        isPersistent: form.RememberMe, lockoutOnFailure: true);
    return result switch
    {
        { Succeeded: true } => Results.Ok(),
        { IsLockedOut: true } => Results.Problem("Too many attempts; try later.", statusCode: 429),
        { IsNotAllowed: true } => Results.Problem("Confirm your e-mail first.", statusCode: 403),
        _ => Results.Unauthorized()
    };
});

record SignUp(string Email, string Password);
record SignInForm(string Email, string Password, bool RememberMe);

go deeper

for a junior

Recall which manager creates users and which signs them in, and read IdentityResult and SignInResult instead of expecting exceptions.

for a middle

Explain the PasswordSignInAsync sequence — confirmation and lockout check, password, two-factor, cookie — and what each SignInResult flag means.

for a senior

Point out the ordering consequences (NotAllowed or LockedOut regardless of password), the scoped lifetimes, and why bypassing SignInManager with HttpContext.SignInAsync skips security checks.

for a principal

Decide when local Identity accounts are the right store at all, versus delegating sign-in to an external provider, and what that changes for support and compliance.

## Two managers, two jobs **ASP.NET Core Identity** is the framework's membership system: it stores local user accounts and signs them in. Its public surface is mostly two classes. | | `UserManager<TUser>` | `SignInManager<TUser>` | |---|---|---| | Concern | the stored user | the signed-in session | | Typical calls | `CreateAsync`, `FindByEmailAsync`, `CheckPasswordAsync`, `ConfirmEmailAsync`, `AddToRoleAsync`, `AccessFailedAsync` | `PasswordSignInAsync`, `SignInAsync`, `SignOutAsync`, `RefreshSignInAsync`, `IsSignedIn` | | Returns | `IdentityResult` (`Succeeded`, `Errors`) | `SignInResult` (`Succeeded`, `IsLockedOut`, `IsNotAllowed`, `RequiresTwoFactor`) | | Talks to | a user store (`IUserStore<TUser>` and friends) | `UserManager`, then the authentication cookie schemes | `TUser` is your user class, usually `IdentityUser` or a subclass. Both managers are registered as **scoped** services, so each request gets its own instance tied to that request's `DbContext`. ## Registering a gardener On a community-garden plot booking site, sign-up creates a user and stores a hashed password: 1. Build the user object with `UserName` and `Email`. 2. Call `UserManager.CreateAsync(user, password)`. It runs every `IUserValidator<TUser>` (for example a duplicate user name) and `IPasswordValidator<TUser>` (the `IdentityOptions.Password` rules), hashes the password with `IPasswordHasher<TUser>` and saves through the store. 3. Read the `IdentityResult`. Failures do not throw; they come back as `IdentityError` entries with a `Code` (`PasswordTooShort`, `PasswordRequiresDigit`, `DuplicateUserName`) and a `Description`. ## Signing in `SignInManager.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure)` runs a fixed sequence: 1. **Pre-sign-in check.** `CanSignInAsync` refuses an unconfirmed account when `SignIn.RequireConfirmedAccount`, `RequireConfirmedEmail` or `RequireConfirmedPhoneNumber` is on; a locked-out user is refused too. Both happen **before** the password is checked. 2. **Password.** `UserManager.CheckPasswordAsync` verifies the hash. On failure, and only if `lockoutOnFailure` is `true`, the failed-attempt counter goes up. 3. **Two-factor.** If the user has two-factor enabled and this browser is not remembered, the result is `RequiresTwoFactor`, and only a short-lived two-factor cookie is written. 4. **Sign-in.** Otherwise the manager builds a `ClaimsPrincipal` through `IUserClaimsPrincipalFactory<TUser>` and signs in with the **`Identity.Application`** cookie scheme. | `SignInResult` | Meaning | |---|---| | `Succeeded` | cookie issued | | `IsLockedOut` | lockout end is in the future | | `IsNotAllowed` | confirmation required and missing | | `RequiresTwoFactor` | password fine, second factor needed | | none of the above | wrong user name or password | ## What sits underneath - **Stores.** `AddEntityFrameworkStores<TContext>()` plugs in EF Core stores over an `IdentityDbContext`, which maps tables such as `AspNetUsers`. Other stores implement the same interfaces. - **Cookies.** `AddIdentity` or `AddIdentityCookies` registers the Identity cookie schemes; the cookie handler's own settings belong to the authentication layer. - **Lower-level calls.** `CheckPasswordSignInAsync` runs steps 1 and 2 without issuing a cookie, and `SignInAsync(user, isPersistent)` issues the cookie without checking a password, for example right after confirming an account. ## Common mistakes - Calling `HttpContext.SignInAsync` with a hand-built principal: it skips the confirmation, lockout and two-factor checks and the claims factory. - Treating a failed `IdentityResult` as an exception path. - Telling the user "wrong password" for every non-success result, hiding lockout and confirmation states the UI should explain.

  • Why does PasswordSignInAsync return IsNotAllowed even when the password is wrong?
    The pre-sign-in check runs before the password check. When confirmation is required and the account is unconfirmed, `CanSignInAsync` fails and the method returns `NotAllowed` without verifying the password. The same ordering returns `LockedOut` for a locked account whatever password is supplied.
  • When would you call CheckPasswordSignInAsync instead of PasswordSignInAsync?
    When you want Identity's checks — confirmation, lockout, password, failed-attempt counting — but issue the session yourself, for example in an endpoint that returns a token rather than setting the Identity cookie. It returns the same `SignInResult` but writes no cookie.
  • What is the lifetime of UserManager and SignInManager in DI?
    Both are registered as scoped (`TryAddScoped`). That matches the EF Core store's `DbContext`, which is scoped too, so resolving either manager from a singleton or caching it across requests captures a disposed context.

  • UserManager.CreateAsync throws an exception when the password breaks a rule.
  • SignInManager stores the password hash and UserManager issues the cookie.
  • PasswordSignInAsync checks the password first, then whether the account is confirmed.
  • Calling HttpContext.SignInAsync with a hand-built principal is equivalent to SignInManager.SignInAsync.
  • UserManager is a singleton, so it can be cached in a static field.