Chapter 23: Authentication: Adding users to your application with Identity
This chapter introduces authentication and ASP.NET Core Identity, previewing how to add, explore, customize, and extend user accounts in web applications.
After this chapter you will be able to
- Authentication and authorization distinction. Distinguish authentication from authorization: authentication creates users and lets them sign in, whereas authorization controls what the current signed-in user can access or do.
- Identity user-management capabilities. Describe ASP.NET Core Identity as the user-management system used in this chapter, including its EF Core integration and its services for creating and managing users, storing and validating passwords, and signing users in and out.
- Authentication and authorization distinction. Distinguish authentication from authorization by stating that authentication determines who a user is, whereas authorization determines what that user is allowed to do. Explain that authentication normally happens before authorization because the application must identify the user before deciding their access.
- Current request principal. Explain that HttpContext.User exposes the principal for the current request, representing ASP.NET Core’s view of who made the request. Describe using this principal when the app needs to identify the current user or determine what they are allowed to do.
- Claims-based user information. Describe a ClaimsPrincipal as a collection of claims, where each claim is one piece of information about the principal with a type and an optional value. Give examples such as name, email, date of birth, or claims related to permissions like HasAdminAccess or IsVipCustomer.
- Initial cookie sign-in flow. Trace how a traditional ASP.NET Core app signs a user in, from submitting an identifier and password through creating an authenticated ClaimsPrincipal and returning an encrypted authentication cookie.
- Subsequent request authentication. Explain how AuthenticationMiddleware turns an incoming authentication cookie into the authenticated HttpContext.User for a later request, and why its location in the middleware pipeline matters.
- Identity security responsibilities. Explain why user management and authentication involve security-sensitive responsibilities, and describe the low-level user-management features ASP.NET Core Identity handles.
- Default Identity UI. Distinguish Identity's low-level services from the optional Microsoft.AspNetCore.Identity.UI package, and describe what the default UI contributes and how it can be replaced or customized.
- Identity adoption guidance. Justify when ASP.NET Core Identity is a strong choice for application-owned users, and distinguish it from cases where an existing solution or an external identity provider may be more appropriate.
- Individual Accounts template setup. Describe how to create the Razor Pages project in Visual Studio by selecting the C# ASP.NET Core Web Application template and setting Authentication Type to Individual Accounts while leaving the other settings at their defaults.
- Identity database preparation. Explain that the Visual Studio Individual Accounts template uses LocalDB and includes SQL Server EF Core migrations, and state that the included migrations must be applied with dotnet ef database update before creating users.
- Identity UI project structure. Describe the main files and folders that the individual-authentication template adds compared with the no-authentication template, including the Identity area, ApplicationDbContext and migrations, and the login partial view.
- Identity services and middleware order. Explain what AddDefaultIdentity() configures and where authentication and authorization belong in the middleware pipeline: AddDefaultIdentity configures IdentityUser-based core services, default UI pages, and token providers; authentication must run before middleware needing an authenticated user, including authorization.
- Identity EF Core foundation. Describe how the default Identity template stores accounts through EF Core: ApplicationDbContext inherits IdentityDbContext, and IdentityUser is the application's user entity.
- Claims-based user extensions. Explain that the default AspNetUsers table contains security-oriented account data rather than arbitrary profile fields, and that additional user information can be added as claims in AspNetUserClaims without changing the schema. Distinguish this from adding properties directly to IdentityUser, which requires database changes.
- User entity and principal. Distinguish the database IdentityUser from the ClaimsPrincipal exposed as HttpContext.User: at login, Identity loads the IdentityUser and its additional stored claims, combines them into a ClaimsPrincipal, and serializes that principal to the authentication cookie.
- Default registration flow. Describe how the default Identity UI registers a user by creating an IdentityUser from an email address and password, then redirects the user to an email-confirmation screen.
- Default account capabilities. Explain that registered users log in through the default UI and, once signed in, can manage their email and password, configure MFA with an authenticator app, and delete their personal data.
- Identity UI customization needs. Describe the key follow-up work commonly needed for the default Identity UI: configure email sending for account confirmation and password recovery, add QR-code generation for MFA setup, and customize or disable the registration and login UI when appropriate.
- Identity integration roadmap. Describe the four steps for adding ASP.NET Core Identity to an existing application: install the Identity NuGet packages, register Identity services in the DI container, add Identity entities to the EF Core data model, and add Razor Page and layout links to the Identity UI.
- Identity package dependencies. State which two NuGet packages an existing application needs to add ASP.NET Core Identity with the default UI, and describe what they provide.
- Identity service registration. Describe how Program.cs registers ASP.NET Core Identity against the application's existing AppDbContext, including the role of ApplicationUser in the registration.
- IdentityDbContext model integration. Describe how to update the application's DbContext to inherit from the generic IdentityDbContext<ApplicationUser>. Explain that IdentityDbContext already inherits from DbContext and supplies the DbSet<T> entities required to store Identity users.
- Identity schema migration. Trace the required EF Core update after changing the context's base class: create a migration named AddIdentitySchema and apply it to the database. Explain that this is necessary because inheriting from IdentityDbContext adds many entities to the EF Core data model.
- Identity UI layout integration. Describe how to make the Identity Razor Pages use the same shared layout as the rest of an existing application by creating an _ViewStart.cshtml file at Areas/Identity/Pages/_ViewStart.cshtml. Explain that this file sets the default layout for the Identity pages to the application’s Layout.cshtml.
- Shared login status widget. Describe adding a _LoginPartial.cshtml partial in Pages/Shared and rendering it from the application’s main _Layout.cshtml. State that the widget displays the current user’s login status and provides registration or sign-in links, using the custom ApplicationUser rather than the default IdentityUser.
- Incremental default UI replacement. Explain how Identity scaffolding generates local Razor Pages that override matching pages in the default Identity UI, allowing a single page to be customized without rebuilding the whole UI.
- View-only override strategy. Explain how to customize only the Register page markup while continuing to use the default UI PageModel: point Register.cshtml's @model directive at the built-in PageModel and remove the scaffolded code-behind and unneeded supporting files. Distinguish this approach from cases where changing page-handler behavior requires retaining and customizing a PageModel.
- Registration-time custom claims. Describe how to add a custom claim such as FullName when an Identity user registers. Explain that the registration page collects the value, creates the ApplicationUser with UserManager.CreateAsync, and then persists the claim with UserManager.AddClaimAsync.
- Current-user claim retrieval. Explain how a custom claim becomes available through the current ClaimsPrincipal after sign-in and how to display its value in a Razor Page or template. State that code can find the first claim of a given type, such as FullName, or use the FindFirstValue extension method; an absent claim produces no displayed value.
What it builds on
- Program.cs file: Defining your application (chapter 3) · The request-level HttpContext created by Kestrel and used to hold request details.
- From request to binding model: Making the request useful (chapter 16) · Model binding of form values such as an email address and password.
- Combining middleware in a pipeline (chapter 4) · Middleware executes in a configured pipeline and earlier middleware runs before later middleware.
- What is EF Core? (chapter 12) · EF Core as the data-access technology used to map application models to a database.
- Registering a data context (chapter 12) · Registering an EF Core data context in an ASP.NET Core application.
- Generating HTML with Razor Pages (chapter 13) · Razor Pages as a way to generate HTML for a web application.
- Using partial views to encapsulate markup (chapter 17) · The role of reusable UI markup in Razor-based applications.
- Using a template to get started (chapter 3) · Using project templates to create an ASP.NET Core application.
Section by section
Introduction
This chapter introduces authentication and ASP.NET Core Identity, previewing how to add, explore, customize, and extend user accounts in web applications.
- Authentication and authorization distinction: Distinguish authentication from authorization: authentication creates users and lets them sign in, whereas authorization controls what the current signed-in user can access or do.
Why it matters: This distinction separates establishing a user's identity from deciding the permissions that identity has. - Identity user-management capabilities: Describe ASP.NET Core Identity as the user-management system used in this chapter, including its EF Core integration and its services for creating and managing users, storing and validating passwords, and signing users in and out.
Why it matters: Identity supplies the standard infrastructure needed to implement account and sign-in features rather than requiring an application to build them all from scratch. - Chapter implementation path: Trace the chapter's planned path: first understand authentication, then explore a template with Identity, add Identity to an existing app, and scaffold and customize default Identity UI pages and user data.
Why it matters: The sequence clarifies why the chapter first explores a complete Identity application before adapting Identity to a real existing app.
Key terms: authentication, authorization, current logged-in user, ASP.NET Core Identity, Identity, Entity Framework Core, EF Core, passwords, default Identity UI, scaffolding
23.1 Introducing authentication and authorization
This section distinguishes authentication from authorization and introduces how ASP.NET Core identifies a signed-in user across requests.
- Authentication and authorization distinction: Distinguish authentication from authorization by stating that authentication determines who a user is, whereas authorization determines what that user is allowed to do. Explain that authentication normally happens before authorization because the application must identify the user before deciding their access.
Why it matters: This distinction is the foundation for adding sign-in features now and access-control rules in the next chapter. - Persistent signed-in identity: Describe the problem authentication must solve after a user signs in: although a password is supplied on one page, later requests must still be associated with that same user. State that the section introduces how a traditional web app recognizes subsequent requests as coming from the signed-in user.
Why it matters: A web app needs a way to recognize the user on later requests in order to provide a continuing signed-in experience.
Key terms: authentication, authorization, sign in, traditional web app, subsequent requests, currently signed-in user
23.1.1 Understanding users and claims in ASP.NET Core
This section explains how ASP.NET Core represents the current request’s user as a claims-based principal stored in HttpContext.User.
- Current request principal: Explain that HttpContext.User exposes the principal for the current request, representing ASP.NET Core’s view of who made the request. Describe using this principal when the app needs to identify the current user or determine what they are allowed to do.
Why it matters: The current principal is where application code obtains user identity and user-related access information for a request. - Claims-based user information: Describe a ClaimsPrincipal as a collection of claims, where each claim is one piece of information about the principal with a type and an optional value. Give examples such as name, email, date of birth, or claims related to permissions like HasAdminAccess or IsVipCustomer.
Why it matters: Claims provide a flexible way to attach identity details and permission-related information to the current user. - Anonymous initial principal: State that Kestrel assigns a principal to every incoming request, but initially it is a generic anonymous, unauthenticated principal with no claims. Distinguish this initial state from a signed-in user, whose sign-in process is introduced in the following section.
Why it matters: This explains why merely receiving a request does not mean ASP.NET Core has identified or authenticated a user.
Key terms: HttpContext, HttpContext.User, principal, ClaimsPrincipal, claim, claim type, claim value, HasAdminAccess, IsVipCustomer, Kestrel
23.1.2 Authentication in ASP.NET Core: Services and middleware
This section traces cookie-based sign-in and subsequent-request authentication in ASP.NET Core, including the roles of services, middleware, and external identity providers.
- Initial cookie sign-in flow: Trace how a traditional ASP.NET Core app signs a user in, from submitting an identifier and password through creating an authenticated ClaimsPrincipal and returning an encrypted authentication cookie.
Why it matters: This explains how a successful login establishes both the user for the current request and a durable identity for later requests. - Subsequent request authentication: Explain how AuthenticationMiddleware turns an incoming authentication cookie into the authenticated HttpContext.User for a later request, and why its location in the middleware pipeline matters.
Why it matters: Middleware can use the current user only after authentication has restored that user's principal. - Authentication and authorization boundaries: Distinguish authentication, which establishes the request's ClaimsPrincipal, from authorization, which decides how to handle unauthenticated or unauthorized access.
Why it matters: Keeping these responsibilities separate makes it easier to configure the right middleware and diagnose access-control behavior. - Identity provider choices: Describe the choice between storing and authenticating users in the application and delegating authentication to an external identity provider, including why delegation is recommended where possible.
Why it matters: An external provider can take on much of the sensitive security work involved in protecting user credentials and data. - Identity security capabilities: State that ASP.NET Core Identity supports locally managed users by handling user persistence and security practices such as password hashing, lockout, and multifactor authentication.
Why it matters: Identity reduces the boilerplate and security risk of implementing local account management yourself.
Key terms: SignInManager, ClaimsPrincipal, HttpContext.User, authentication cookie, model binding, AuthenticationMiddleware, authentication services, AuthorizationMiddleware, identity provider, OpenID Connect
23.2 What is ASP.NET Core Identity?
This section explains what ASP.NET Core Identity provides for storing and managing application users, where its boundaries are, and why it is usually safer than building user management yourself.
- Identity security responsibilities: Explain why user management and authentication involve security-sensitive responsibilities, and describe the low-level user-management features ASP.NET Core Identity handles.
Why it matters: Identity avoids making you implement security details, such as password protection and defenses against common account attacks, from scratch. - Identity storage flexibility: Describe Identity's default EF Core persistence model and explain how custom stores let an application load and save user details differently when EF Core is not desired.
Why it matters: You can use Identity's user-management capabilities without being locked into EF Core as your application's data-access choice. - Default Identity UI: Distinguish Identity's low-level services from the optional Microsoft.AspNetCore.Identity.UI package, and describe what the default UI contributes and how it can be replaced or customized.
Why it matters: Starting with the supplied UI gives a functioning sign-in flow while preserving the option to tailor the user experience later. - Identity adoption guidance: Justify when ASP.NET Core Identity is a strong choice for application-owned users, and distinguish it from cases where an existing solution or an external identity provider may be more appropriate.
Why it matters: Choosing an established identity solution can reduce the security risk of storing and managing users' personal information.
Key terms: ASP.NET Core Identity, claims, strong hashing algorithm, MFA, brute-force attacks, account lockout, EF Core, stores, user details, database integration
23.3 Creating a project that uses ASP.NET Core Identity
This section introduces examining a template-generated ASP.NET Core project to see Identity working in a real application and locate its integration points.
- Identity template project overview: Describe the purpose of examining the default ASP.NET Core template generated with Identity and the aspects of it this section will explore: its working code, project structure, and where Identity fits.
Why it matters: Seeing the generated application provides a concrete basis for understanding how ASP.NET Core Identity is integrated into a project.
Key terms: ASP.NET Core Identity, ASP.NET Core templates, Identity
23.3.1 Creating the project from a template
This section creates a Razor Pages application with individual-account Identity from a template and prepares its database so users can be registered.
- Individual Accounts template setup: Describe how to create the Razor Pages project in Visual Studio by selecting the C# ASP.NET Core Web Application template and setting Authentication Type to Individual Accounts while leaving the other settings at their defaults.
Why it matters: This template generates the starting application and Identity boilerplate used throughout the rest of the chapter. - Identity database preparation: Explain that the Visual Studio Individual Accounts template uses LocalDB and includes SQL Server EF Core migrations, and state that the included migrations must be applied with dotnet ef database update before creating users.
Why it matters: Identity cannot store newly registered users until its database schema has been created by the migrations. - CLI template alternative: State the equivalent .NET CLI command for creating the application, including that dotnet new webapp -au Individual creates it with individual accounts and that the CLI defaults to SQLite unless --use-local-db is supplied.
Why it matters: The CLI provides an alternative to Visual Studio and makes the database-provider difference explicit.
Key terms: ASP.NET Core Web Application, Razor Pages, Authentication Type, Individual Accounts, dotnet restore, LocalDB, EF Core migrations, SQL Server, dotnet ef database update, database provider
23.3.2 Exploring the template in Solution Explorer
This section tours the Identity-enabled project template, showing its default UI structure, service registration, and authentication middleware placement.
- Identity UI project structure: Describe the main files and folders that the individual-authentication template adds compared with the no-authentication template, including the Identity area, ApplicationDbContext and migrations, and the login partial view.
Why it matters: Recognizing which pieces come from the template helps you find the Identity UI, data setup, and navigation links you may need to customize. - Identity area UI overrides: Explain how the Microsoft.AspNetCore.Identity.UI default UI supplies account Razor Pages in the Identity area, and how an application can override a supplied page by creating its corresponding file under Areas/Identity/Pages.
Why it matters: The default UI avoids writing common account pages, while targeted overrides let you customize only what you need. - Area-aware Identity links: Describe how _LoginPartial.cshtml generates links to Identity Razor Pages by combining a Razor Page path such as /Account/Login with the Identity area route value through the asp-area Tag Helper attribute.
Why it matters: Links must identify the Identity area so routing can find account pages outside the application's main Pages hierarchy. - Identity services and middleware order: Explain what AddDefaultIdentity() configures and where authentication and authorization belong in the middleware pipeline: AddDefaultIdentity configures IdentityUser-based core services, default UI pages, and token providers; authentication must run before middleware needing an authenticated user, including authorization.
Why it matters: Correct service registration and middleware ordering ensure that users are identified and authorization policies can act on that identity.
Key terms: Areas, Identity area, default UI, ApplicationDbContext, migrations, _LoginPartial.cshtml, Microsoft.AspNetCore.Identity.UI, Areas/Identity/Pages, _ViewStart.cshtml, _Layout.cshtml
23.3.3 The ASP.NET Core Identity data model
Explains how ASP.NET Core Identity stores users and related authentication data with EF Core, and how database users become authenticated claims principals.
- Identity EF Core foundation: Describe how the default Identity template stores accounts through EF Core: ApplicationDbContext inherits IdentityDbContext, and IdentityUser is the application's user entity.
Why it matters: This explains why an Identity-enabled application gets a complete user data model without defining all of its tables yourself. - Identity database migration: Describe how to create or update the Identity database by pointing the connection string at the desired database and running the EF Core migration update command from the project folder. State that the CLI creates the database if it does not already exist.
Why it matters: Applying the migrations reveals and creates the database schema on which the default Identity implementation relies. - Identity schema responsibilities: Summarize the roles of the main default Identity tables: AspNetUsers holds user profiles, AspNetUserClaims holds a user's claims, login and token tables support third-party sign-ins, and role tables model roles and their claims. Explain that Identity normally manages these tables rather than application code accessing them directly.
Why it matters: A basic map of the schema makes Identity's features understandable while avoiding unnecessary direct database work. - Claims-based user extensions: Explain that the default AspNetUsers table contains security-oriented account data rather than arbitrary profile fields, and that additional user information can be added as claims in AspNetUserClaims without changing the schema. Distinguish this from adding properties directly to IdentityUser, which requires database changes.
Why it matters: Choosing claims for extra data is a simple way to extend the default user model without immediately changing the database schema. - User entity and principal: Distinguish the database IdentityUser from the ClaimsPrincipal exposed as HttpContext.User: at login, Identity loads the IdentityUser and its additional stored claims, combines them into a ClaimsPrincipal, and serializes that principal to the authentication cookie.
Why it matters: This distinction explains why request-time authentication uses HttpContext.User and claims rather than the database entity itself.
Key terms: IdentityDbContext, IdentityUser, ApplicationDbContext, EF Core, migrations, connection string, dotnet ef, project folder, AspNetUsers, AspNetUserClaims
23.3.4 Interacting with ASP.NET Core Identity
This section tours ASP.NET Core Identity’s default UI, its built-in account flows, and the common customizations an application needs.
- Default registration flow: Describe how the default Identity UI registers a user by creating an IdentityUser from an email address and password, then redirects the user to an email-confirmation screen.
Why it matters: Registration is the entry point through which the default Identity UI adds users to an application. - Default account capabilities: Explain that registered users log in through the default UI and, once signed in, can manage their email and password, configure MFA with an authenticator app, and delete their personal data.
Why it matters: The default UI provides common account-management features so an application does not need to build all of them from scratch. - Identity UI customization needs: Describe the key follow-up work commonly needed for the default Identity UI: configure email sending for account confirmation and password recovery, add QR-code generation for MFA setup, and customize or disable the registration and login UI when appropriate.
Why it matters: The shipped UI covers common flows, but external services and application-specific requirements determine what must be added or changed. - Identity option configuration: State that the AddDefaultIdentity() configuration lambda can customize Identity options, including the default unique-email requirement and password length and complexity requirements.
Why it matters: Identity’s registration rules can be adapted to an application’s account and password policies.
Key terms: default UI, IdentityUser, registration page, email confirmation, Login page, Identity UI, MFA, authenticator app, management pages, email-sending service
23.4 Adding ASP.NET Core Identity to an existing project
This section introduces the plan and intended result for adding default ASP.NET Core Identity user accounts to an existing EF Core Razor Pages recipe application.
- Identity integration roadmap: Describe the four steps for adding ASP.NET Core Identity to an existing application: install the Identity NuGet packages, register Identity services in the DI container, add Identity entities to the EF Core data model, and add Razor Page and layout links to the Identity UI.
Why it matters: These steps turn an existing EF Core application into one that can support built-in user accounts. - Default Identity user experience: State that the completed recipe application has the default registration, login, and manage-account screens, plus a persistent top-right widget that shows the current user's login status.
Why it matters: These visible features confirm that users can access the default Identity account experience in the existing application. - Integration scope boundaries: Distinguish this initial integration from Identity customization: it adds default ASP.NET Core Identity to an existing EF Core app without configuring external login providers, email confirmation, or MFA.
Why it matters: Keeping the initial setup focused makes it easier to establish working local user accounts before adding more authentication features.
Key terms: ASP.NET Core Identity, NuGet packages, dependency injection (DI) container, EF Core data model, Identity entities, Identity UI, registration page, login screen, manage account screen, login status
23.4.1 Configuring the ASP.NET Core Identity services
This section shows how to configure an existing EF Core application to use ASP.NET Core Identity and its default UI.
- Identity package dependencies: State which two NuGet packages an existing application needs to add ASP.NET Core Identity with the default UI, and describe what they provide.
Why it matters: The packages supply the Identity, EF Core integration, and Razor Pages UI dependencies required before the application can use Identity. - Identity service registration: Describe how Program.cs registers ASP.NET Core Identity against the application's existing AppDbContext, including the role of ApplicationUser in the registration.
Why it matters: Registering Identity services and connecting them to the existing context lets Identity store and manage application users through EF Core. - Authentication middleware placement: Explain that adding AuthenticationMiddleware after UseRouting() is optional in this application because WebApplication adds it automatically.
Why it matters: This prevents redundant middleware configuration while clarifying where authentication middleware belongs when it is explicitly added.
Key terms: Microsoft.AspNetCore.Identity.EntityFrameworkCore, Microsoft.AspNetCore.Identity.UI, default UI, dotnet restore, Program.cs, ASP.NET Core Identity services, AppDbContext, ApplicationUser, EF Core, AuthenticationMiddleware
23.4.2 Updating the EF Core data model to support Identity
This section adapts an existing EF Core data model for ASP.NET Core Identity by introducing an application user type, inheriting from IdentityDbContext, and migrating the added schema to the database.
- ApplicationUser derived user type: Explain why the section creates an ApplicationUser type even though using the built-in IdentityUser directly is not strictly required. State that creating the derived type early makes adding user-specific properties later easier than retrofitting the type.
Why it matters: Starting with an application-specific user class leaves room for your application's future user data. - IdentityDbContext model integration: Describe how to update the application's DbContext to inherit from the generic IdentityDbContext<ApplicationUser>. Explain that IdentityDbContext already inherits from DbContext and supplies the DbSet<T> entities required to store Identity users.
Why it matters: Changing the context base class incorporates Identity's persistence model into an existing EF Core application. - Identity schema migration: Trace the required EF Core update after changing the context's base class: create a migration named AddIdentitySchema and apply it to the database. Explain that this is necessary because inheriting from IdentityDbContext adds many entities to the EF Core data model.
Why it matters: The database must be migrated so it has the schema needed to persist Identity data.
Key terms: ApplicationUser, IdentityUser, DbContext, IdentityDbContext, IdentityDbContext<ApplicationUser>, DbSet<T>, EF Core data model, migration, AddIdentitySchema, database
23.4.3 Updating the Razor views to link to the Identity UI
This subsection links an existing application’s Razor layout and login widget to ASP.NET Core Identity’s default UI.
- Identity UI layout integration: Describe how to make the Identity Razor Pages use the same shared layout as the rest of an existing application by creating an _ViewStart.cshtml file at Areas/Identity/Pages/_ViewStart.cshtml. Explain that this file sets the default layout for the Identity pages to the application’s Layout.cshtml.
Why it matters: A shared layout makes the built-in Identity pages look and navigate like the rest of the application. - Shared login status widget: Describe adding a _LoginPartial.cshtml partial in Pages/Shared and rendering it from the application’s main _Layout.cshtml. State that the widget displays the current user’s login status and provides registration or sign-in links, using the custom ApplicationUser rather than the default IdentityUser.
Why it matters: Putting the login widget in the shared layout gives users visible account actions throughout the application.
Key terms: _ViewStart.cshtml, Areas/Identity/Pages, Layout.cshtml, Identity Razor Pages, default UI, _LoginPartial.cshtml, Pages/Shared, _Layout.cshtml, ApplicationUser, IdentityUser
23.5 Customizing a page in ASP.NET Core Identity’s default UI
This section shows how to scaffold and selectively override an ASP.NET Core Identity default UI page while retaining as much of the built-in implementation as possible.
- Incremental default UI replacement: Explain how Identity scaffolding generates local Razor Pages that override matching pages in the default Identity UI, allowing a single page to be customized without rebuilding the whole UI.
Why it matters: Selective overrides let you tailor user-facing Identity pages without having to own every page in the authentication UI. - Register page scaffolding workflow: Describe the Visual Studio workflow for scaffolding the Account/Register page: ensure the project has the required code-generation and EF Core tools packages and builds, choose the Identity scaffolded item, select Account/Register and the application's AppDbContext, and add the generated page.
Why it matters: Following this workflow produces an overrideable Register page and the supporting files it needs to integrate with the remaining default UI. - View-only override strategy: Explain how to customize only the Register page markup while continuing to use the default UI PageModel: point Register.cshtml's @model directive at the built-in PageModel and remove the scaffolded code-behind and unneeded supporting files. Distinguish this approach from cases where changing page-handler behavior requires retaining and customizing a PageModel.
Why it matters: Reusing the built-in PageModel avoids maintaining complex code-behind when the desired change is only to the page's look or displayed content. - Customization maintenance tradeoff: Justify using the smallest necessary override by describing the maintenance cost of scaffolded code: customized files may need updating when a new ASP.NET Core version changes the default UI.
Why it matters: Keeping fewer copied Identity files reduces the code your application must maintain across framework upgrades.
Key terms: scaffolding, default Identity UI, Razor Pages, override, Microsoft.VisualStudio.Web.CodeGeneration.Design, Microsoft.EntityFrameworkCore.Tools, Identity scaffolder, Account/Register, AppDbContext, Areas/Identity/Pages/Account
23.6 Managing users: Adding custom data to users
This section shows how to add custom claims to Identity users during registration and read those claims from the current user in Razor Pages and templates.
- Registration-time custom claims: Describe how to add a custom claim such as FullName when an Identity user registers. Explain that the registration page collects the value, creates the ApplicationUser with UserManager.CreateAsync, and then persists the claim with UserManager.AddClaimAsync.
Why it matters: Custom claims let an application attach user-specific information to an authenticated identity. - Current-user claim retrieval: Explain how a custom claim becomes available through the current ClaimsPrincipal after sign-in and how to display its value in a Razor Page or template. State that code can find the first claim of a given type, such as FullName, or use the FindFirstValue extension method; an absent claim produces no displayed value.
Why it matters: Reading claims from the current principal lets pages personalize output using data attached to the signed-in user. - Custom-data storage choices: Distinguish automatically granting claims to every user at registration from adding claims manually after registration for selected users. Describe why permission claims such as IsAdmin commonly require a separate, appropriately secured user-management UI, and note that extending IdentityUser with a property is an alternative for editable profile data such as a name.
Why it matters: Choosing the appropriate place and time to manage user data helps prevent users from changing their own permissions.
Key terms: Claim, ApplicationUser, UserManager<ApplicationUser>, CreateAsync, AddClaimAsync, Register.cshtml, ClaimsPrincipal, HttpContext.User, SignInAsync, Type
23.7 Summary
This summary recaps how ASP.NET Core identifies users with claims-based authentication and how ASP.NET Core Identity supplies database-backed user management and login support.
Where this is used later
- Introduction to authorization (chapter 24) · It introduces authorization after authentication has established the current user.
- Authentication for APIs and distributed applications (chapter 25) · It applies authentication principles to APIs and distributed applications.
- Authorization in ASP.NET Core (chapter 24) · Authorization uses the request user to prevent anonymous users from accessing application resources.
- Using policies for claims-based authorization (chapter 24) · Claims-based authorization policies evaluate claims associated with the current principal.
- Preventing anonymous users from accessing your application (chapter 24) · Preventing anonymous access depends on distinguishing anonymous principals from authenticated users.
- Understanding bearer token authentication (chapter 25) · Bearer-token authentication is contrasted with the cookie-based persistence model described here.
- Adding JWT bearer authentication to minimal APIs (chapter 25) · Adding JWT bearer authentication applies the same middleware-based idea with a different credential format.
- Centralizing authentication in an identity provider (chapter 25) · Centralizing authentication in an identity provider extends this choice to distributed applications.
Concepts explained in this chapter
- ASP.NET Core IdentityASP.NET Core Identity is an ASP.NET Core membership system that provides user accounts, authentication, authorization integration, and related identity-management services.
- Identity Razor PagesASP.NET Core Identity UI is the built-in Razor Pages library that provides standard user-account and authentication interfaces for ASP.NET Core Identity.
- ClaimsPrincipalClaimsPrincipal is a .NET security object that represents an authenticated user through a collection of claims and identities.
- identity providerA third-party identity service is an externally operated identity provider that supplies authentication and identity-management capabilities to applications.
- IdentityUserIdentityUser is the standard ASP.NET Core Identity entity type representing a user account and its core account properties.
- authenticationAuthentication is the process of determining the identity of the subject that made a request.
- claimA claim is a statement about an authenticated subject, represented as a type and value, that can support authorization decisions.
- password hashingA password hash is a one-way derived value stored instead of the plaintext password for later password verification.
- cookieAn authentication cookie is a client-side HTTP cookie containing serialized authentication state used to recognize a signed-in user across requests.
- multifactor authenticationMultifactor authentication is authentication that requires evidence from multiple independent credential or verification factors.
- AuthenticationMiddlewareAuthenticationMiddleware is ASP.NET Core middleware that authenticates the user associated with an HTTP request.
- SignInManager<T>SignInManager<T> is an ASP.NET Core Identity service for signing users in and out and managing request authentication state.
- IdentityDbContextIdentityDbContext<TUser> is an Entity Framework Core database context base class that maps ASP.NET Core Identity data for a specified user type.
- migrationA database migration is a versioned change that updates a database schema to match changes in an application's data model.
- UserManager<T>UserManager<T> is an ASP.NET Core Identity service for creating, retrieving, updating, and managing users and their associated credentials and data.
- schemaA database schema is the structural definition of a database's tables, columns, keys, relationships, and related objects.
- user managementUser management is the administration of application user accounts, credentials, profile details, claims, and account security settings.
- AddDefaultIdentityAddDefaultIdentity is an ASP.NET Core Identity service-registration extension method that configures core Identity services, a user type, default UI pages, and token providers.
- AuthorizationMiddlewareAuthorizationMiddleware is ASP.NET Core middleware that determines whether an authenticated user may access a selected endpoint.
- areaAn area is an ASP.NET Core organizational feature that groups Razor Pages into a separate hierarchy.
- asp-area attributeThe asp-area attribute is an ASP.NET Core Tag Helper attribute that specifies the area associated with a generated link.
- identity areaThe Identity area is the ASP.NET Core Identity UI area containing pages for user registration, login, and account management.
- identity database schemaThe Identity database schema is the set of database structures used to persist ASP.NET Core Identity users and related authentication data.
- middlewareMiddleware is a request-processing component that can inspect, modify, or handle HTTP requests and responses within an ASP.NET Core pipeline.
- Identity scaffolderThe Identity scaffolder is a .NET code-generation tool that generates customizable ASP.NET Core Identity UI files.
- PageModelA PageModel code-behind file is the C# source file containing the handler methods and state for a Razor Page.
- scaffoldScaffolding is the process of generating project files that provide a starting point for customization.
- HttpContext.UserHttpContext.User is the ASP.NET Core property containing the ClaimsPrincipal associated with the current HTTP request.
- AddClaimAsyncAddClaimAsync is an ASP.NET Core Identity operation that asynchronously adds a claim to a user account.
- AspNetUsersAspNetUsers is the ASP.NET Core Identity database table that stores serialized user entities.
- authorizationAuthorization is the process of determining whether an authenticated subject has permission to perform an operation or access a resource.
- UseAuthenticationUseAuthentication is an ASP.NET Core extension method that adds authentication middleware at a specified point in the request pipeline.
- claims-based approachClaims-based authorization is an authorization approach that evaluates claims associated with an authenticated identity to decide whether access is permitted.
- dotnet newdotnet new is a .NET CLI command that creates projects from installed templates.
- software templateA project template is a predefined set of files and settings used to generate the initial structure of a software project.
- _ViewStart.cshtml_ViewStart.cshtml is a conventionally named Razor file containing code that executes before Razor views or pages in its directory and descendant directories are rendered.
- layoutA Razor layout is a shared Razor template that defines common page structure and renders the content of individual pages within it.
- data modelA database model represents the application data stored in a database and the structure used to work with that data.
- dbcontextDbContext is the Entity Framework Core base class that coordinates database connections, entity tracking, querying, and persistence for a data model.
- subtemplateA partial Razor view is a reusable Razor view fragment that can be rendered within another view or layout.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
