AspNetCore.Docs/aspnetcore/security/authentication/identity.md

20 KiB

title author description ms.author ms.date uid
Introduction to Identity on ASP.NET Core rick-anderson Use Identity with an ASP.NET Core app. Learn how to set password requirements (RequireDigit, RequiredLength, RequiredUniqueChars, and more). riande 12/05/2019 security/authentication/identity

Introduction to Identity on ASP.NET Core

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

By Rick Anderson

ASP.NET Core Identity:

  • Is an API that supports user interface (UI) login functionality.
  • Manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more.

Users can create an account with the login information stored in Identity or they can use an external login provider. Supported external login providers include Facebook, Google, Microsoft Account, and Twitter.

The Identity source code is available on GitHub. Scaffold Identity and view the generated files to review the template interaction with Identity.

Identity is typically configured using a SQL Server database to store user names, passwords, and profile data. Alternatively, another persistent store can be used, for example, Azure Table Storage.

In this topic, you learn how to use Identity to register, log in, and log out a user. For more detailed instructions about creating apps that use Identity, see the Next Steps section at the end of this article.

Microsoft identity platform is:

  • An evolution of the Azure Active Directory (Azure AD) developer platform.
  • Unrelated to ASP.NET Core Identity.

[!INCLUDE]

View or download the sample code (how to download)).

Create a Web app with authentication

Create an ASP.NET Core Web Application project with Individual User Accounts.

Visual Studio

  • Select File > New > Project.
  • Select ASP.NET Core Web Application. Name the project WebApp1 to have the same namespace as the project download. Click OK.
  • Select an ASP.NET Core Web Application, then select Change Authentication.
  • Select Individual User Accounts and click OK.

.NET Core CLI

dotnet new webapp --auth Individual -o WebApp1

The preceding command creates a Razor web app using SQLite. To create the web app with LocalDB, run the following command:

dotnet new webapp --auth Individual -uld -o WebApp1

The generated project provides ASP.NET Core Identity as a Razor Class Library. The Identity Razor Class Library exposes endpoints with the Identity area. For example:

  • /Identity/Account/Login
  • /Identity/Account/Logout
  • /Identity/Account/Manage

Apply migrations

Apply the migrations to initialize the database.

Visual Studio

Run the following command in the Package Manager Console (PMC):

PM> Update-Database

.NET Core CLI

Migrations are not necessary at this step when using SQLite. For LocalDB, run the following command:

dotnet ef database update

Test Register and Login

Run the app and register a user. Depending on your screen size, you might need to select the navigation toggle button to see the Register and Login links.

[!INCLUDE]

Configure Identity services

Services are added in ConfigureServices. The typical pattern is to call all the Add{Service} methods, and then call all the services.Configure{Service} methods.

[!code-csharp]

The preceding highlighted code configures Identity with default option values. Services are made available to the app through dependency injection.

Identity is enabled by calling xref:Microsoft.AspNetCore.Builder.AuthAppBuilderExtensions.UseAuthentication*. UseAuthentication adds authentication middleware to the request pipeline.

[!code-csharp]

The template-generated app doesn't use authorization. app.UseAuthorization is included to ensure it's added in the correct order should the app add authorization. UseRouting, UseAuthentication, UseAuthorization, and UseEndpoints must be called in the order shown in the preceding code.

For more information on IdentityOptions and Startup, see xref:Microsoft.AspNetCore.Identity.IdentityOptions and Application Startup.

Scaffold Register, Login, and LogOut

Visual Studio

Add the Register, Login, and LogOut files. Follow the Scaffold identity into a Razor project with authorization instructions to generate the code shown in this section.

.NET Core CLI

If you created the project with name WebApp1, run the following commands. Otherwise, use the correct namespace for the ApplicationDbContext:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet aspnet-codegenerator identity -dc WebApp1.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.Logout"

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semicolons in the file list or put the file list in double quotes, as the preceding example shows.

For more information on scaffolding Identity, see Scaffold identity into a Razor project with authorization.


Examine Register

When a user clicks the Register link, the RegisterModel.OnPostAsync action is invoked. The user is created by CreateAsync on the _userManager object. _userManager is provided by dependency injection):

[!code-csharp]

If the user was created successfully, the user is logged in by the call to _signInManager.SignInAsync.

See account confirmation for steps to prevent immediate login at registration.

Log in

The Login form is displayed when:

  • The Log in link is selected.
  • A user attempts to access a restricted page that they aren't authorized to access or when they haven't been authenticated by the system.

When the form on the Login page is submitted, the OnPostAsync action is called. PasswordSignInAsync is called on the _signInManager object (provided by dependency injection).

[!code-csharp]

The base Controller class exposes a User property that can be accessed from controller methods. For instance, you can enumerate User.Claims and make authorization decisions. For more information, see xref:security/authorization/introduction.

Log out

The Log out link invokes the LogoutModel.OnPost action.

[!code-csharp]

In the preceding code, the code return RedirectToPage(); needs to be a redirect so that the browser performs a new request and the identity for the user gets updated.

SignOutAsync clears the user's claims stored in a cookie.

Post is specified in the Pages/Shared/_LoginPartial.cshtml:

[!code-csharp]

Test Identity

The default web project templates allow anonymous access to the home pages. To test Identity, add [Authorize]:

[!code-csharp]

If you are signed in, sign out. Run the app and select the Privacy link. You are redirected to the login page.

Explore Identity

To explore Identity in more detail:

Identity Components

All the Identity-dependent NuGet packages are included in the ASP.NET Core shared framework.

The primary package for Identity is Microsoft.AspNetCore.Identity. This package contains the core set of interfaces for ASP.NET Core Identity, and is included by Microsoft.AspNetCore.Identity.EntityFrameworkCore.

Migrating to ASP.NET Core Identity

For more information and guidance on migrating your existing Identity store, see Migrate Authentication and Identity.

Setting password strength

See Configuration for a sample that sets the minimum password requirements.

AddDefaultIdentity and AddIdentity

xref:Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionUIExtensions.AddDefaultIdentity* was introduced in ASP.NET Core 2.1. Calling AddDefaultIdentity is similar to calling the following:

See AddDefaultIdentity source for more information.

Next Steps

::: moniker-end

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

By Rick Anderson

ASP.NET Core Identity is a membership system that adds login functionality to ASP.NET Core apps. Users can create an account with the login information stored in Identity or they can use an external login provider. Supported external login providers include Facebook, Google, Microsoft Account, and Twitter.

Identity can be configured using a SQL Server database to store user names, passwords, and profile data. Alternatively, another persistent store can be used, for example, Azure Table Storage.

View or download the sample code (how to download)).

In this topic, you learn how to use Identity to register, log in, and log out a user. For more detailed instructions about creating apps that use Identity, see the Next Steps section at the end of this article.

AddDefaultIdentity and AddIdentity

xref:Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionUIExtensions.AddDefaultIdentity* was introduced in ASP.NET Core 2.1. Calling AddDefaultIdentity is similar to calling the following:

See AddDefaultIdentity source for more information.

Create a Web app with authentication

Create an ASP.NET Core Web Application project with Individual User Accounts.

Visual Studio

  • Select File > New > Project.
  • Select ASP.NET Core Web Application. Name the project WebApp1 to have the same namespace as the project download. Click OK.
  • Select an ASP.NET Core Web Application, then select Change Authentication.
  • Select Individual User Accounts and click OK.

.NET Core CLI

dotnet new webapp --auth Individual -o WebApp1

The generated project provides ASP.NET Core Identity as a Razor Class Library. The Identity Razor Class Library exposes endpoints with the Identity area. For example:

  • /Identity/Account/Login
  • /Identity/Account/Logout
  • /Identity/Account/Manage

Apply migrations

Apply the migrations to initialize the database.

Visual Studio

Run the following command in the Package Manager Console (PMC):

PM> Update-Database

.NET Core CLI

dotnet ef database update

Test Register and Login

Run the app and register a user. Depending on your screen size, you might need to select the navigation toggle button to see the Register and Login links.

[!INCLUDE]

Configure Identity services

Services are added in ConfigureServices. The typical pattern is to call all the Add{Service} methods, and then call all the services.Configure{Service} methods.

[!code-csharp]

The preceding code configures Identity with default option values. Services are made available to the app through dependency injection.

Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication middleware to the request pipeline.

[!code-csharp]

For more information, see the IdentityOptions Class and Application Startup.

Scaffold Register, Login, and LogOut

Follow the Scaffold identity into a Razor project with authorization instructions to generate the code shown in this section.

Visual Studio

Add the Register, Login, and LogOut files.

.NET Core CLI

If you created the project with name WebApp1, run the following commands. Otherwise, use the correct namespace for the ApplicationDbContext:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet aspnet-codegenerator identity -dc WebApp1.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.Logout"

PowerShell uses semicolon as a command separator. When using PowerShell, escape the semicolons in the file list or put the file list in double quotes, as the preceding example shows.


Examine Register

When a user clicks the Register link, the RegisterModel.OnPostAsync action is invoked. The user is created by CreateAsync on the _userManager object. _userManager is provided by dependency injection):

[!code-csharp]

If the user was created successfully, the user is logged in by the call to _signInManager.SignInAsync.

Note: See account confirmation for steps to prevent immediate login at registration.

Log in

The Login form is displayed when:

  • The Log in link is selected.
  • A user attempts to access a restricted page that they aren't authorized to access or when they haven't been authenticated by the system.

When the form on the Login page is submitted, the OnPostAsync action is called. PasswordSignInAsync is called on the _signInManager object (provided by dependency injection).

[!code-csharp]

The base Controller class exposes a User property that you can access from controller methods. For instance, you can enumerate User.Claims and make authorization decisions. For more information, see xref:security/authorization/introduction.

Log out

The Log out link invokes the LogoutModel.OnPost action.

[!code-csharp]

SignOutAsync clears the user's claims stored in a cookie.

Post is specified in the Pages/Shared/_LoginPartial.cshtml:

[!code-csharp]

Test Identity

The default web project templates allow anonymous access to the home pages. To test Identity, add [Authorize] to the Privacy page.

[!code-csharp]

If you are signed in, sign out. Run the app and select the Privacy link. You are redirected to the login page.

Explore Identity

To explore Identity in more detail:

Identity Components

All the Identity dependent NuGet packages are included in the Microsoft.AspNetCore.App metapackage.

The primary package for Identity is Microsoft.AspNetCore.Identity. This package contains the core set of interfaces for ASP.NET Core Identity, and is included by Microsoft.AspNetCore.Identity.EntityFrameworkCore.

Migrating to ASP.NET Core Identity

For more information and guidance on migrating your existing Identity store, see Migrate Authentication and Identity.

Setting password strength

See Configuration for a sample that sets the minimum password requirements.

Next Steps

::: moniker-end