Upgrade to 4.0Changelog
Guides

Register users

Create accounts with an email and password, a passkey, or a GitHub or Google account.

AuthEndpoints creates accounts with a password, a passkey, GitHub or Google, or an emailed code. Every account needs an email address. When RequireConfirmedAccount is true (the default), password and passkey registration do not sign the user in. GitHub and Google sign the user in when the provider returns a verified email.

Examples use the password facade prefix /auth. External sign-in is mapped by the host, under /auth/external in these steps.

Compare the registration methods

MethodPackageEndpointsSends a confirmation emailCSRFSigns in on successTwo-factor
Email and passwordAuthEndpointsPOST /auth/register, then GET /auth/confirmEmailYesNoNoThe user turns on 2FA later.
PasskeyAuthEndpoints. Mapped when Passkeys.ServerDomain is set.POST /auth/passkeys/register/options, then POST /auth/passkeys/registerYesYesOnly when CanSignInAsync passes. By default it does not.Passkey sign-in skips 2FA.
GitHub or GoogleAuthEndpoints, plus AuthEndpoints.OAuth.GitHub or AuthEndpoints.OAuth.GoogleGET /auth/external/login/{provider}, then the callbackNoNo. The OAuth state cookie protects the callback.Yes, when the provider email is verifiedOAuth sign-in skips 2FA.

A duplicate email never tells the caller that the address is taken. Password registration returns 200. Passkey registration returns the generic 400 "Unable to complete registration." GitHub and Google refuse the sign-in with auto_link_disabled unless you turn on AutoLinkByEmail.

Get a CSRF token

Cookie-session and JWT cookie-refresh passkey ceremonies require an antiforgery token. Password registration does not. Identity bearer and JWT body refresh do not require a token on the passkey ceremony. On the password facade, a cookie session and JWT cookie refresh get the token from GET /auth/csrfToken and send it in the RequestVerificationToken header:

const { csrfToken } = await fetch('/auth/csrfToken', { credentials: 'include' }).then(r => r.json());

A missing or wrong token returns 400 with the plain-text body Invalid or missing CSRF token. The Antiforgery (CSRF) rules page lists every route that needs a token.

Register with an email and password

Before you start, register a real IEmailSender<TUser>. In Production, startup fails while Identity's no-op sender is registered, unless you set RequireEmailSenderInProduction to false. Set password rules with ConfigureIdentity.

  1. Send the email and password to POST /auth/register. The body is Identity's RegisterRequest.
    const response = await fetch('/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });
    
  2. Check the response:
    • 200 with an empty body: show a "Check your email" screen. The user is not signed in. A duplicate email also returns 200, so use the same copy.
    • 400 validation problem: show the errors. Examples are InvalidEmail and the password-rule codes such as PasswordTooShort.
    • 429: the AuthEndpoints.AccountAbuse rate limit (10 requests per minute per IP) rejected the request.
  3. AuthEndpoints calls IEmailSender<TUser>.SendConfirmationLinkAsync with a link to GET /auth/confirmEmail?userId=...&code=.... The user name is set to the email.
  4. The user opens the link. The response depends on EmailConfirmation.ConfirmEmailRedirectUri:
    • Not set: 200 with the text "Thank you for confirming your email.", or 401 when the link is not valid.
    • Set: 302 to that URI with status=confirmed or status=failed, and flow=confirm. See Email confirmation.
  5. Sign the user in. See Sign users in.

Resend the confirmation email

POST /auth/resendConfirmationEmail sends the link again to the signed-in user's email. It requires a signed-in user and a CSRF token, and it ignores the email field in the body.

When RequireConfirmedAccount is true, an unconfirmed user cannot sign in. That user cannot call this endpoint. Resend helps only when RequireConfirmedAccount is false, or after a signed-in user changes their email. AuthEndpoints has no anonymous resend endpoint.

Register with a passkey

A passkey account has no password. On the password facade, set Passkeys.ServerDomain. That maps passkey sign-in, including this register route, and passkey management. Before you start:

  • Set Passkeys.ServerDomain. It is required in Production.
  • Use a TUser with a string or Guid key, such as IdentityUser or IdentityUser<Guid>.
  • To choose the minted user id, register an IPasskeyUserIdFactory with AddPasskeyUserIdFactory. The default id is Guid.NewGuid().

Send credentials: 'include' on both requests. The Identity ceremony state lives in the TwoFactorUserIdScheme cookie (Identity.TwoFactorUserId). That cookie is single-use state, not a credential, and the client must send it between the options call and the verify call. A cookie session and JWT cookie refresh also send the CSRF header. Identity bearer and JWT body refresh do not.

  1. Collect the email address.
  2. Get creation options from POST /auth/passkeys/register/options with { "email" }. A cookie session and JWT cookie refresh send the CSRF header. The endpoint returns WebAuthn creation options even when the email is taken. An invalid email returns a 400 validation problem with the key Email.
  3. Call navigator.credentials.create. If the user cancels, stop. Do not call the register endpoint.
  4. Send the credential to POST /auth/passkeys/register with { "email", "credentialJson" }. A cookie session and JWT cookie refresh send the CSRF header. A cookie session sets the application cookie when sign-in is allowed. Add ?useSessionCookies=false for a persistent cookie. useCookies is ignored on that session.
    const headers = { 'Content-Type': 'application/json', 'RequestVerificationToken': csrfToken };
    
    const options = await fetch('/auth/passkeys/register/options', {
      method: 'POST', credentials: 'include', headers, body: JSON.stringify({ email })
    }).then(r => r.json());
    
    const credential = await navigator.credentials.create({
      publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options)
    });
    
    const response = await fetch('/auth/passkeys/register', {
      method: 'POST', credentials: 'include', headers,
      body: JSON.stringify({ email, credentialJson: JSON.stringify(credential) })
    });
    
  5. On 200 { "credentialId": "..." } with no session, the account exists and cannot sign in yet, because the email is not confirmed. Show the same "Check your email" screen as password registration. When sign-in is allowed, a cookie session also sets the application cookie and still returns credentialId. Other sessions and the 400 shapes are in Responses and errors.
  6. AuthEndpoints sends the same confirmation email as password registration. The user confirms with the same GET /auth/confirmEmail link.
  7. After confirmation, the user signs in with the passkey. See Sign in with a passkey.

Passwordless registration never adds a passkey to an existing account. To add a passkey to a signed-in account, see Add, rename, and remove passkeys.

Register with GitHub or Google

External sign-in is compose-only. MapPasswordAuth does not map it. The endpoint types are in AuthEndpoints. The GitHub and Google packages only register handlers.

  1. Install the provider packages:
    dotnet add package AuthEndpoints.OAuth.GitHub
    dotnet add package AuthEndpoints.OAuth.Google
    
  2. Register the services. AddExternalAuthEndpoints<TUser>() returns an ExternalAuthBuilder. AddGitHub and AddGoogle validate ClientId and ClientSecret at startup.
    builder.Services.AddExternalAuthEndpoints<AppUser>(o =>
    {
        o.RequireVerifiedEmail = true; // default
        o.DefaultReturnUrl = "/";
    })
    .AddGitHub(o =>
    {
        o.ClientId = builder.Configuration["Authentication:GitHub:ClientId"]!;
        o.ClientSecret = builder.Configuration["Authentication:GitHub:ClientSecret"]!;
    })
    .AddGoogle(o =>
    {
        o.ClientId = builder.Configuration["Authentication:Google:ClientId"]!;
        o.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]!;
    });
    
  3. Map the routes:
    var external = app.MapGroup("/auth/external");
    external.MapExternalAuthProvider<AppUser>("GitHub"); // GET login/github, login/github/callback
    external.MapExternalAuthProvider<AppUser>("Google"); // GET login/google, login/google/callback
    
  4. Register the handler callback paths with each identity provider: /signin-github for GitHub and /signin-google for Google.
  5. Host an error page at ErrorPath (default /auth/external/error).
  6. Start the flow with a top-level navigation, not fetch:
    window.location.assign('/auth/external/login/github?returnUrl=' + encodeURIComponent('/dashboard'));
    

The callback creates an account when no local user has this provider login, the provider returned an email, and no local user has that email. A verified email is enough. There is no option to stop that creation. RequireVerifiedEmail defaults to true and refuses an unverified email.

The new user has no password. EmailConfirmed matches the provider's verified flag. AuthEndpoints links the login, signs the user in, and redirects to returnUrl. It does not send a confirmation email.

If RequireVerifiedEmail is false and the email is not verified, the callback still creates the account. It then refuses the sign-in with user_not_allowed, because RequireConfirmedAccount applies. How GitHub and Google prove the email is in External OAuth.

When the callback refuses, it redirects to ErrorPath?error=...&error_description=.... A client that prefers application/json over text/html gets a problem details response instead. The error codes are listed in Responses and errors.

To finish in a JWT session, pass AuthEndpointsSession.Jwt to MapExternalAuthProvider or MapExternalAuthEndpoints. Map MapJwtSessionEndpoints on the JWT prefix. Refresh transport stays Cookie. After the redirect, the client calls POST /auth/refresh with a CSRF token. Body transport throws at map time. AuthEndpointsSession.IdentityBearer writes the token body and does not redirect. See Sign-in completers.

Sign up with an emailed code

Password registration on POST /auth/register is separate. To create a confirmed user from an emailed code, set AllowSignUp to true. It defaults to false. That user has no password. The steps are in Sign in with an emailed code.

What registration does not support

AuthEndpoints does not include these features:

  • Sign-up with a phone number or SMS.
  • Sign-up with a user name and no email.
  • An anonymous endpoint that resends the confirmation email.
  • Built-in Apple or Microsoft providers. You can add a custom provider with IExternalAuthProvider and AddProvider.
  • Setting a first password through POST /auth/manage/info. That endpoint requires oldPassword when you send newPassword. An account with no password uses POST /auth/manage/password when password sign-in is mapped. See Change a user's email or password.