aspnetcore/security/authentication/scaffold-identity.md
:::moniker range=">= aspnetcore-8.0"
ASP.NET Core Identity scaffolding adds ASP.NET Core Identity to Blazor Web Apps and Blazor Server apps. After the scaffolder adds the Identity Razor components to the app, you can customize the components to suit your app's requirements.
Although the scaffolder generates the necessary C# code to scaffold Identity into the app, you must update the project's database with an Entity Framework (EF) Core database migration to complete the process. This article explains the steps required to migrate a database.
Inspect the changes after running the Identity scaffolder. We recommend using GitHub or another source control system that shows file changes with a revert changes feature.
Services are required when using two-factor authentication (2FA), account confirmation and password recovery, and other security features with Identity. Services or service stubs aren't generated when scaffolding Identity. Services to enable these features must be added manually.
ASP.NET Core provides ASP.NET Core Identity as a Razor class library (RCL). Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity RCL. You might want to generate source code so you can modify the code and change the behavior. For example, you could instruct the scaffolder to generate the code used in registration. Customized Identity code overrides the default implementation provided by the Identity RCL. To gain full control of the UI and not use the default RCL, see the Create full Identity UI source section.
Applications that do not include authentication can apply the scaffolder to add the RCL Identity package. You have the option of selecting Identity code to be generated.
Although the scaffolder generates most of the necessary code, you need to update your project to complete the process. This document explains the steps needed to complete an Identity scaffolding update.
We recommend using a source control system that shows file differences and allows you to back out of changes. Inspect the changes after running the Identity scaffolder.
Services are required when using Two Factor Authentication, Account confirmation and password recovery, and other security features with Identity. Services or service stubs aren't generated when scaffolding Identity. Services to enable these features must be added manually. For example, see Require Email Confirmation.
Typically, apps created with individual accounts should not create a new data context.
This section applies to Blazor Web Apps and Blazor Server apps.
Run the Identity scaffolder:
To add the required NuGet packages and tools, execute the following .NET CLI commands in a command shell opened to the project's root folder.
Paste all of the following commands at the prompt (>) of the command shell. When you paste multiple commands, a warning appears stating that multiple commands will execute. Select the Paste anyway button.
When you paste multiple commands, all but the last one runs. Press <kbd>Enter</kbd> to run the last command.
The following commands assume that you're using a SQL Server database and the SQL Server Entity EF Core database provider package (Microsoft.EntityFrameworkCore.SqlServer). If you're using a different database, swap the EF Core database provider package. The following providers are supported by the scaffolding tool†:
Microsoft.EntityFrameworkCore.SqlServerMicrosoft.EntityFrameworkCore.SqliteMicrosoft.EntityFrameworkCore.CosmosNpgsql.EntityFrameworkCore.PostgreSQL†The SQL Server, SQLite, and Cosmos database provider packages are owned, maintained, and supported by Microsoft. The PostgreSQL database provider package is owned, maintained, and supported by The Npgsql Development Team (npgsql/efcore.pg Github repository)).
dotnet tool install --global dotnet-aspnet-codegenerator
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
[!IMPORTANT] After the first five commands execute, make sure that you press <kbd>Enter</kbd> on the keyboard to execute the last command.
The preceding commands add:
aspnet-codegenerator scaffolding toolMicrosoft.VisualStudio.Web.CodeGeneration.Design for scaffoldingRun the following command to list the Identity scaffolder options:
dotnet aspnet-codegenerator identity -h
In the project folder, run the Identity scaffolder with the options you want. To scaffold Identity with the default Identity UI and the minimum number of files, run the following command:
dotnet aspnet-codegenerator identity --useDefaultUI
The generated Identity database code requires EF Core Migrations. The following steps explain how to create and apply a migration to the database.
Visual Studio Connected Services are used to add an EF Core migration and update the database.
In Solution Explorer, double-click Connected Services. In the SQL Server Express LocalDB area of Service Dependencies, select the ellipsis (...) followed by Add migration.
Give the migration a Migration name, such as CreateIdentitySchema, which is a name that describes the migration. Wait for the database context to load in the DbContext class names field, which may take a few seconds. Select Finish to create the migration.
Select the Close button after the operation finishes.
Select the ellipsis (...) again followed by the Update database command.
The Update database with the latest migration dialog opens. Wait for the DbContext class names field to update and for prior migrations to load, which may take a few seconds. Select the Finish button.
Select the Close button after the operation finishes.
The update database command executes the Up method migrations that haven't been applied in a migration code file created by the scaffolder. In this case, the command executes the Up method in the Migrations/{TIME STAMP}_{MIGRATION NAME}.cs file, which creates the Identity tables, constraints, and indexes. The {TIME STAMP} placeholder is a time stamp, and the {MIGRATION NAME} placeholder is the migration name.
From the project's root folder, execute the following .NET CLI command to add a migration. The {MIGRATION NAME} placeholder is used to name the migration, such as CreateIdentitySchema. Any name can be used, but the convention is to use a name that describes the migration.
dotnet ef migrations add {MIGRATION NAME}
Example:
dotnet ef migrations add CreateIdentitySchema
After the preceding command completes, update the database with the update command.
dotnet ef database update
The update command executes the Up method migrations that haven't been applied in a migration code file created by the scaffolder. In this case, the command executes the Up method in the Migrations/{TIME STAMP}_{MIGRATION NAME}.cs file, which creates the Identity tables, constraints, and indexes. The {TIME STAMP} placeholder is a time stamp, and the {MIGRATION NAME} placeholder is the migration name.
Client-side Blazor apps (Standalone Blazor WebAssembly) use their own Identity UI approaches and can't use ASP.NET Core Identity scaffolding.
For more information, see the Blazor Security and Identity articles.
<a name="RPNA"></a>
<a name="efm"></a>
<a name="useauthentication"></a>
<!-- ### Enable authentication Update the `Startup` class with code similar to the following: [!code-csharp[](scaffold-identity/3.1sample/StartupRP.cs?name=snippet)] [!INCLUDE[](~/includes/scaffold-identity/hsts.md)] -->Optional: Add the login partial (_LoginPartial) to the layout file:
Optional: Add the login partial (_LoginPartial) to the Views/Shared/_Layout.cshtml file:
Add MapRazorPages to Program.cs as shown in the following highlighted code:
<a name="full"></a>
To maintain full control of the Identity UI, run the Identity scaffolder and select Override all files.
<!-- uld option: Use Local DB, not SQLite dotnet new webapp -au Individual -uld -o RPauth cd RPauth dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation" -->If xref:Microsoft.AspNetCore.Identity.PasswordOptions are configured in Startup.ConfigureServices, [StringLength] attribute configuration might be required for the Password property in scaffolded Identity pages. InputModel Password properties are found in the following files:
Areas/Identity/Pages/Account/Register.cshtml.csAreas/Identity/Pages/Account/ResetPassword.cshtml.csThis section shows how to disable the register page but the approach can be used to disable any page.
To disable user registration:
Scaffold Identity. Include Account.Register, Account.Login, and Account.RegisterConfirmation. For example:
dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation"
Update Areas/Identity/Pages/Account/Register.cshtml.cs so users can't register from this endpoint:
Update Areas/Identity/Pages/Account/Register.cshtml to be consistent with the preceding changes:
Comment out or remove the registration link from Areas/Identity/Pages/Account/Login.cshtml
@*
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
*@
Update the Areas/Identity/Pages/Account/RegisterConfirmation page.
PageModel: [AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
public IActionResult OnGet()
{
return Page();
}
}
Provide a mechanism to add users outside the web app. Options to add users include:
The following code outlines one approach to adding users:
The following code outlines adding a user:
A similar approach can be followed for production scenarios.
To prevent publishing static Identity assets to the web root, see xref:security/authentication/identity#prevent-publish-of-static-identity-assets.
:::moniker-end
:::moniker range=">= aspnetcore-6.0 < aspnetcore-8.0"
ASP.NET Core provides ASP.NET Core Identity as a Razor class library (RCL). Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity RCL. You might want to generate source code so you can modify the code and change the behavior. For example, you could instruct the scaffolder to generate the code used in registration. Generated code takes precedence over the same code in the Identity RCL. To gain full control of the UI and not use the default RCL, see the section Create full Identity UI source.
Applications that do not include authentication can apply the scaffolder to add the RCL Identity package. You have the option of selecting Identity code to be generated.
Although the scaffolder generates most of the necessary code, you need to update your project to complete the process. This document explains the steps needed to complete an Identity scaffolding update.
We recommend using a source control system that shows file differences and allows you to back out of changes. Inspect the changes after running the Identity scaffolder.
Services are required when using Two Factor Authentication, Account confirmation and password recovery, and other security features with Identity. Services or service stubs aren't generated when scaffolding Identity. Services to enable these features must be added manually. For example, see Require Email Confirmation.
Typically, apps created with individual accounts should not create a new data context.
<a name="RPNA"></a>
<a name="efm"></a>
<a name="useauthentication"></a>
<!-- ### Enable authentication Update the `Startup` class with code similar to the following: [!code-csharp[](scaffold-identity/3.1sample/StartupRP.cs?name=snippet)] [!INCLUDE[](~/includes/scaffold-identity/hsts.md)] -->Optional: Add the login partial (_LoginPartial) to the layout file:
Optional: Add the login partial (_LoginPartial) to the Views/Shared/_Layout.cshtml file:
Add MapRazorPages to Program.cs as shown in the following highlighted code:
Because server-side Blazor apps use Razor Pages Identity pages, the styling of the UI changes when a visitor navigates between Identity pages and components. You have two options to address the incongruous styles:
ASP.NET Core Identity is designed to work in the context of HTTP request and response communication, which isn't the primary client-server communication model in Blazor apps. ASP.NET Core apps that use ASP.NET Core Identity for user management should use Razor Pages instead of Razor components for Identity-related UI, such as user registration, login, logout, and other user management tasks.
Because xref:Microsoft.AspNetCore.Identity.SignInManager%601 and xref:Microsoft.AspNetCore.Identity.UserManager%601 aren't supported in Razor components, we recommend using web API to manage Identity actions from Razor components via a server-side Identity-enabled ASP.NET Core app. For guidance on creating web APIs for Blazor apps, see xref:blazor/call-web-api.
An approach to using Razor components for Identity instead of Razor pages is to build your own custom Identity Razor components, but Microsoft doesn't recommend or support the approach. For additional context, explore the following discussions. In the following discussions, code examples in issue comments and code examples cross-linked in non-Microsoft GitHub repositories aren't supported by Microsoft but might be helpful to some developers:
SigninManager<T> not being supported in Razor Components (dotnet/aspnetcore #34095)For additional assistance when seeking to build custom Identity Razor components or searching for third-party Razor components, we recommend the following resources:
blazor) (Public support forum)The Identity pages layout and styles can be modified to produce pages that use styles similar to the default Blazor theme. This approach isn't covered by the documentation.
Client-side Blazor apps use their own Identity UI approaches and can't use ASP.NET Core Identity scaffolding. Server-side ASP.NET Core apps of hosted Blazor solutions can follow the Razor Pages/MVC guidance in this article and are configured just like any other type of ASP.NET Core app that supports Identity.
The Blazor framework doesn't include Razor component versions of Identity UI pages. Identity UI Razor components can be custom built or obtained from unsupported third-party sources.
For more information, see the Blazor Security and Identity articles.
<a name="full"></a>
To maintain full control of the Identity UI, run the Identity scaffolder and select Override all files.
<!-- uld option: Use Local DB, not SQLite dotnet new webapp -au Individual -uld -o RPauth cd RPauth dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation" -->If xref:Microsoft.AspNetCore.Identity.PasswordOptions are configured in Startup.ConfigureServices, [StringLength] attribute configuration might be required for the Password property in scaffolded Identity pages. InputModel Password properties are found in the following files:
Areas/Identity/Pages/Account/Register.cshtml.csAreas/Identity/Pages/Account/ResetPassword.cshtml.csThis section shows how to disable the register page but the approach can be used to disable any page.
To disable user registration:
Scaffold Identity. Include Account.Register, Account.Login, and Account.RegisterConfirmation. For example:
dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation"
Update Areas/Identity/Pages/Account/Register.cshtml.cs so users can't register from this endpoint:
Update Areas/Identity/Pages/Account/Register.cshtml to be consistent with the preceding changes:
Comment out or remove the registration link from Areas/Identity/Pages/Account/Login.cshtml
@*
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
*@
Update the Areas/Identity/Pages/Account/RegisterConfirmation page.
PageModel: [AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
public IActionResult OnGet()
{
return Page();
}
}
Provide a mechanism to add users outside the web app. Options to add users include:
The following code outlines one approach to adding users:
The following code outlines adding a user:
A similar approach can be followed for production scenarios.
To prevent publishing static Identity assets to the web root, see xref:security/authentication/identity#prevent-publish-of-static-identity-assets.
:::moniker-end
:::moniker range="< aspnetcore-6.0"
ASP.NET Core provides ASP.NET Core Identity as a Razor class library (RCL). Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity RCL. You might want to generate source code so you can modify the code and change the behavior. For example, you could instruct the scaffolder to generate the code used in registration. Generated code takes precedence over the same code in the Identity RCL. To gain full control of the UI and not use the default RCL, see the section Create full Identity UI source.
Applications that do not include authentication can apply the scaffolder to add the RCL Identity package. You have the option of selecting Identity code to be generated.
Although the scaffolder generates most of the necessary code, you need to update your project to complete the process. This document explains the steps needed to complete an Identity scaffolding update.
We recommend using a source control system that shows file differences and allows you to back out of changes. Inspect the changes after running the Identity scaffolder.
Services are required when using Two Factor Authentication, Account confirmation and password recovery, and other security features with Identity. Services or service stubs aren't generated when scaffolding Identity. Services to enable these features must be added manually. For example, see Require Email Confirmation.
When scaffolding Identity with a new data context into a project with existing individual accounts, open Startup.ConfigureServices and remove the calls to:
AddDbContextAddDefaultIdentityFor example, AddDbContext and AddDefaultIdentity are commented out in the following code:
The preceding code comments out the code that is duplicated in Areas/Identity/IdentityHostingStartup.cs
Typically, apps created with individual accounts should not create a new data context.
Update the Startup class with code similar to the following:
Identity is configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.
<a name="efm"></a>
<a name="useauthentication"></a>
Update the Startup class with code similar to the following:
Optional: Add the login partial (_LoginPartial) to the layout file:
Some Identity options are configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.
Optional: Add the login partial (_LoginPartial) to the Views/Shared/_Layout.cshtml file:
Move the Pages/Shared/_LoginPartial.cshtml file to Views/Shared/_LoginPartial.cshtml.
Identity is configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.
Update the Startup class with code similar to the following:
Identity is configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.
Because server-side Blazor apps use Razor Pages Identity pages, the styling of the UI changes when a visitor navigates between Identity pages and components. You have two options to address the incongruous styles:
An approach to using components for Identity instead of pages is to build Identity components. Because SignInManager and UserManager aren't supported in Razor components, use web API endpoints in the Blazor app to process user account actions.
The Identity pages layout and styles can be modified to produce pages that use styles similar to the default Blazor theme. This approach isn't covered by the documentation.
Some Identity options are configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.
Client-side Blazor apps use their own Identity UI approaches and can't use ASP.NET Core Identity scaffolding. Server-side ASP.NET Core apps of hosted Blazor solutions can follow the Razor Pages/MVC guidance in this article and are configured just like any other type of ASP.NET Core app that supports Identity.
The Blazor framework doesn't include Razor component versions of Identity UI pages. Identity UI Razor components can be custom built or obtained from unsupported third-party sources.
For more information, see the Blazor Security and Identity articles.
<a name="full"></a>
To maintain full control of the Identity UI, run the Identity scaffolder and select Override all files.
The following highlighted code shows the changes to replace the default Identity UI with Identity in an ASP.NET Core 2.1 web app. You might want to do this to have full control of the Identity UI.
The default Identity is replaced in the following code:
The following code sets the xref:Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions.LoginPath%2A, xref:Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions.LogoutPath%2A, and xref:Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions.AccessDeniedPath%2A):
Register an IEmailSender implementation, for example:
If xref:Microsoft.AspNetCore.Identity.PasswordOptions are configured in Startup.ConfigureServices, [StringLength] attribute configuration might be required for the Password property in scaffolded Identity pages. InputModel Password properties are found in the following files:
Areas/Identity/Pages/Account/Register.cshtml.csAreas/Identity/Pages/Account/ResetPassword.cshtml.csThis section shows how to disable the register page but the approach can be used to disable any page.
To disable user registration:
Scaffold Identity. Include Account.Register, Account.Login, and Account.RegisterConfirmation. For example:
dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation"
Update Areas/Identity/Pages/Account/Register.cshtml.cs so users can't register from this endpoint:
Update Areas/Identity/Pages/Account/Register.cshtml to be consistent with the preceding changes:
Comment out or remove the registration link from Areas/Identity/Pages/Account/Login.cshtml
@*
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
*@
Update the Areas/Identity/Pages/Account/RegisterConfirmation page.
PageModel: [AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
public IActionResult OnGet()
{
return Page();
}
}
Provide a mechanism to add users outside the web app. Options to add users include:
The following code outlines one approach to adding users:
The following code outlines adding a user:
A similar approach can be followed for production scenarios.
To prevent publishing static Identity assets to the web root, see xref:security/authentication/identity#prevent-publish-of-static-identity-assets.
Changes to authentication code to ASP.NET Core 2.1 or later
:::moniker-end