Skip to content

Latest commit

 

History

History
1136 lines (744 loc) · 45.6 KB

File metadata and controls

1136 lines (744 loc) · 45.6 KB
title Add, download, and delete user data to Identity in an ASP.NET Core project
ai-usage ai-assisted
author wadepickett
description Learn how to add custom user data to Identity in an ASP.NET Core project. Delete data per GDPR.
ms.author wpickett
ms.custom mvc
ms.date 04/02/2026
uid security/authentication/add-user-data

Add, download, and delete custom user data to Identity in an ASP.NET Core project

This article shows how to:

  • Add custom user data to an ASP.NET Core web app.
  • Mark the custom user data model with the xref:Microsoft.AspNetCore.Identity.PersonalDataAttribute attribute so it's automatically available for download and deletion. Making the data able to be downloaded and deleted helps meet GDPR requirements.

The project sample is created from a Razor Pages web app, but the instructions are similar for an ASP.NET Core MVC web app.

View or download sample code (how to download)

Prerequisites

:::moniker range=">= aspnetcore-10.0"

[!INCLUDE ]

Quick start: Add two custom properties

For the common case of adding two custom properties such as FirstName and LastName:

  1. Create a new ASP.NET Core project with Individual Accounts authentication
  2. Scaffold Identity to override the Register and Manage/Index pages
  3. Add custom properties such as FirstName and LastName to the user class, with the [PersonalData] attribute.
  4. Update the Register and Manage/Index pages to include input fields for your properties
  5. Create and apply a migration
  6. Test registration and profile management

The sections below provide detailed step-by-step instructions for this process.

Create a web app

You can create either a Razor Pages or MVC web app. Both use the same Identity Razor Pages UI.

Razor Pages

  • From the Visual Studio File menu, select New > Project/Solution....
  • Select ASP.NET Core Web App (Razor Pages) > Next
  • Name the project WebApp1 if you want it to match the namespace of the download sample code. Select Next.
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new webapp -au Individual -o WebApp1

MVC

  • From the Visual Studio File menu, select New > Project/Solution....
  • Select ASP.NET Core Web App (Model-View-Controller) > Next
  • Name the project WebApp1 if you want it to match the namespace of the download sample code. Select Next.
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new mvc -au Individual -o WebApp1

Note

Identity UI is implemented as a Razor Class Library. When you create an MVC project with authentication, the Identity pages are served from the Razor Class Library, which means your MVC project uses Razor Pages for Identity even though the rest of the project uses MVC controllers and views.

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml for Razor Pages or ~/Views/Shared/_Layout.cshtml for MVC
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Program.cs
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Update the layout

See Layout changes for instructions to add sign-in and sign-out links to every page.

Add a migration for the custom user data

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData
Update-Database
dotnet ef migrations add CustomUserData
dotnet ef database update

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page.

Troubleshooting

If you encounter issues:

Symptom Likely Cause Solution
Custom fields don't appear in registration form Forgot to update Register.cshtml Ensure you've scaffolded and modified Areas/Identity/Pages/Account/Register.cshtml
Custom data not saving Forgot to add migration or update database Run dotnet ef migrations add CustomUserData then dotnet ef database update
Custom fields not in downloaded data Missing [PersonalData] attribute Add [PersonalData] attribute to properties in your user class
Build errors after scaffolding Package version mismatch Ensure all Identity packages match your target framework version

:::moniker-end

:::moniker range=">= aspnetcore-9.0 < aspnetcore-10.0"

[!INCLUDE ]

Note

The code samples and instructions for .NET 9 reference the 10.x sample folder. The code is identical between .NET 9 and .NET 10 for this scenario. Only the target framework and package versions differ in the project file.

Quick start: Add two custom properties

For the common case of adding two custom properties such as FirstName and LastName:

  1. Create a new ASP.NET Core project with Individual Accounts authentication
  2. Scaffold Identity to override the Register and Manage/Index pages
  3. Add custom properties such as FirstName and LastName to the user class, with the [PersonalData] attribute.
  4. Update the Register and Manage/Index pages to include input fields for your properties
  5. Create and apply a migration
  6. Test registration and profile management

The sections below provide detailed step-by-step instructions for this process.

Create a web app

You can create either a Razor Pages or MVC web app. Both use the same Identity Razor Pages UI.

Razor Pages

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web App > Next
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new webapp -au Individual -o WebApp1

MVC

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web App (Model-View-Controller) > Next
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new mvc -au Individual -o WebApp1

Note

Identity UI is implemented as a Razor Class Library. When you create an MVC project with authentication, the Identity pages are served from the Razor Class Library, which means your MVC project uses Razor Pages for Identity even though the rest of the project uses MVC controllers and views.

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml for Razor Pages or ~/Views/Shared/_Layout.cshtml for MVC
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Program.cs
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Update the layout

See Layout changes for instructions to add sign-in and sign-out links to every page.

Add a migration for the custom user data

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData
Update-Database
dotnet ef migrations add CustomUserData
dotnet ef database update

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page.

Troubleshooting

If you encounter issues:

Symptom Likely Cause Solution
Custom fields don't appear in registration form Forgot to update Register.cshtml Ensure you've scaffolded and modified Areas/Identity/Pages/Account/Register.cshtml
Custom data not saving Forgot to add migration or update database Run dotnet ef migrations add CustomUserData then dotnet ef database update
Custom fields not in downloaded data Missing [PersonalData] attribute Add [PersonalData] attribute to properties in your user class
Build errors after scaffolding Package version mismatch Ensure all Identity packages match your target framework version

:::moniker-end

:::moniker range=">= aspnetcore-8.0 < aspnetcore-9.0"

[!INCLUDE ]

Note

The code samples and instructions for .NET 8 reference the 10.x sample folder. The code is identical between .NET 8 and .NET 10 for this scenario. Only the target framework and package versions differ in the project file.

Quick start: Add two custom properties

For a simple scenario where you want to add just a couple of custom properties, such as FirstName and LastName to your Identity user:

  1. Create a new ASP.NET Core project with Individual Accounts authentication
  2. Scaffold Identity to override the Register and Manage/Index pages
  3. Add your custom properties to the user class (e.g., FirstName, LastName) with the [PersonalData] attribute
  4. Update the Register and Manage/Index pages to include input fields for your properties
  5. Create and apply a migration
  6. Test registration and profile management

The sections below provide detailed step-by-step instructions for this process.

Create a web app

You can create either a Razor Pages or MVC web app. Both use the same Identity Razor Pages UI.

Razor Pages

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web App > Next
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new webapp -au Individual -o WebApp1

MVC

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web App (Model-View-Controller) > Next
  • Select Authentication type > Individual Accounts > Create
  • Build and run the project.
dotnet new mvc -au Individual -o WebApp1

Note

Identity UI is implemented as a Razor Class Library. When you create an MVC project with authentication, the Identity pages are served from the Razor Class Library, which means your MVC project uses Razor Pages for Identity even though the rest of the project uses MVC controllers and views.

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml for Razor Pages or ~/Views/Shared/_Layout.cshtml for MVC
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Program.cs
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Update the layout

See Layout changes for instructions to add sign-in and sign-out links to every page.

Add a migration for the custom user data

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData
Update-Database
dotnet ef migrations add CustomUserData
dotnet ef database update

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page.

Troubleshooting

If you encounter issues:

Symptom Likely Cause Solution
Custom fields don't appear in registration form Forgot to update Register.cshtml Ensure you've scaffolded and modified Areas/Identity/Pages/Account/Register.cshtml
Custom data not saving Forgot to add migration or update database Run dotnet ef migrations add CustomUserData then dotnet ef database update
Custom fields not in downloaded data Missing [PersonalData] attribute Add [PersonalData] attribute to properties in your user class
Build errors after scaffolding Package version mismatch Ensure all Identity packages match your target framework version

:::moniker-end

:::moniker range=">= aspnetcore-6.0 < aspnetcore-8.0"

[!INCLUDE ]

Create a Razor web app

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web Application > OK
  • Select Web Application > OK
  • Build and run the project.
dotnet new webapp -o WebApp1

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Program.cs
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Update the layout

See Layout changes for instructions to add sign-in and sign-out links to every page.

Add a migration for the custom user data

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData
Update-Database
dotnet ef migrations add CustomUserData
dotnet ef database update

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page. :::moniker-end

:::moniker range=">= aspnetcore-3.0 < aspnetcore-6.0"

[!INCLUDE ]

Create a Razor web app

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web Application > OK
  • Select Web Application > OK
  • Build and run the project.
dotnet new webapp -o WebApp1

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Startup.Configure.
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Add a migration for the custom user data

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData
Update-Database
dotnet ef migrations add CustomUserData
dotnet ef database update

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page.

Add claims to Identity using IUserClaimsPrincipalFactory<ApplicationUser>

Note

This section isn't an extension of the previous tutorial. To apply the following steps to the app built using the tutorial, see this GitHub issue.

Additional claims can be added to ASP.NET Core Identity by using the IUserClaimsPrincipalFactory<T> interface. This class can be added to the app in the Startup.ConfigureServices method. Add the custom implementation of the class as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, 
        AdditionalUserClaimsPrincipalFactory>();

The demo code uses the ApplicationUser class. This class adds an IsAdmin property which is used to add the additional claim.

public class ApplicationUser : IdentityUser
{
    public bool IsAdmin { get; set; }
}

The AdditionalUserClaimsPrincipalFactory implements the UserClaimsPrincipalFactory interface. A new role claim is added to the ClaimsPrincipal.

public class AdditionalUserClaimsPrincipalFactory 
        : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AdditionalUserClaimsPrincipalFactory( 
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager, 
        IOptions<IdentityOptions> optionsAccessor) 
        : base(userManager, roleManager, optionsAccessor)
    {}

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);
        var identity = (ClaimsIdentity)principal.Identity;

        var claims = new List<Claim>();
        if (user.IsAdmin)
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "admin"));
        }
        else
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "user"));
        }

        identity.AddClaims(claims);
        return principal;
    }
}

The additional claim can then be used in the app. In a Razor Page, the IAuthorizationService instance can be used to access the claim value.

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@if ((await AuthorizationService.AuthorizeAsync(User, "IsAdmin")).Succeeded)
{
    <ul class="mr-auto navbar-nav">
        <li class="nav-item">
            <a class="nav-link" asp-controller="Admin" asp-action="Index">ADMIN</a>
        </li>
    </ul>
}

:::moniker-end

:::moniker range="< aspnetcore-3.0"

[!INCLUDE ]

Create a Razor web app

  • From the Visual Studio File menu, select New > Project. Name the project WebApp1 if you want it to match the namespace of the download sample code.
  • Select ASP.NET Core Web Application > OK
  • Select ASP.NET Core 2.2 in the dropdown
  • Select Web Application > OK
  • Build and run the project.
dotnet new webapp -o WebApp1

Run the Identity scaffolder

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > Add.
  • In the Add Identity dialog, the following options:
    • Select the existing layout file ~/Pages/Shared/_Layout.cshtml
    • Select the following files to override:
      • Account/Register
      • Account/Manage/Index
    • Select the + button to create a new Data context class. Accept the type (WebApp1.Models.WebApp1Context if the project is named WebApp1).
    • Select the + button to create a new User class. Accept the type (WebApp1User if the project is named WebApp1) > Add.
  • Select Add.

If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

[!INCLUDE]

Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder:

dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semi-colons in the file list or put the file list in double quotes.


Follow the instructions in Migrations, UseAuthentication, and layout to perform the following steps:

  • Create a migration and update the database.
  • Add UseAuthentication to Startup.Configure.
  • Add <partial name="_LoginPartial" /> to the layout file.
  • Test the app:
    • Register a user
    • Select the new user name (next to the Logout link). You might need to expand the window or select the navigation bar icon to show the user name and other links.
    • Select the Personal Data tab.
    • Select the Download button and examine the PersonalData.json file.
    • Test the Delete button, which deletes the logged on user.

Add custom user data to the Identity DB

Update the IdentityUser derived class with custom properties. If you named the project WebApp1, the file is named Areas/Identity/Data/WebApp1User.cs. Update the file with the following code:

[!code-csharp]

Properties with the PersonalData attribute are:

  • Deleted when the Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml Razor Page calls UserManager.Delete.
  • Included in the downloaded data by the Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml Razor Page.

Update the Account/Manage/Index.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Manage/Index.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Manage/Index.cshtml with the following highlighted markup:

[!code-cshtml]

Update the Account/Register.cshtml page

Update the InputModel in Areas/Identity/Pages/Account/Register.cshtml.cs with the following highlighted code:

[!code-csharp]

Update the Areas/Identity/Pages/Account/Register.cshtml with the following highlighted markup:

[!code-cshtml]

Build the project.

Add a migration for the custom user data

The custom properties added to the WebApp1User Identity user class need to be reflected in the database. A migration is needed now to generate the SQL required to add the new columns, and then the database needs to be updated to apply those changes.

The Identity scaffolder created a new DbContext (WebApp1Context) alongside the original ApplicationDbContext from the project template. You must specify the new WebApp1Context Identity DbContext to use when running migration commands.

In the Visual Studio Package Manager Console:

Add-Migration CustomUserData -Context WebApp1Context
Update-Database -Context WebApp1Context
dotnet ef migrations add CustomUserData --context WebApp1Context
dotnet ef database update --context WebApp1Context

Test create, view, download, delete custom user data

Test the app:

  • Register a new user.
  • View the custom user data on the /Identity/Account/Manage page.
  • Download and view the users personal data from the /Identity/Account/Manage/PersonalData page.

:::moniker-end