Dec 01, 2018 In this tutorial you will learn to Authenticate Users in Identity Membership System in ASP.NET Core. Follow the steps, given in this tutorial, with.
-->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
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.
- 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.
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 initialise the database.
Run the following command in the Package Manager Console (PMC):
PM> Update-Database
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.
View the Identity database
- From the View menu, select SQL Server Object Explorer (SSOX).
- Navigate to (localdb)MSSQLLocalDB(SQL Server 13). Right-click on dbo.AspNetUsers > View Data:
There are many third party tools you can download to manage and view a SQLite database, for example DB Browser for SQLite.
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.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.Services are made available to the application through dependency injection.
Identity is enabled for the application by calling
UseAuthentication
in the Configure
method. UseAuthentication
adds authentication middleware to the request pipeline.These services are made available to the application through dependency injection.
Identity is enabled for the application by calling
UseIdentity
in the Configure
method. UseIdentity
adds cookie-based authentication middleware to the request pipeline.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.
Add the Register, Login, and LogOut files.
If you created the project with name WebApp1, run the following commands. Otherwise, use the correct namespace for the
ApplicationDbContext
: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):When a user clicks the Register link, the
Register
action is invoked on AccountController
. The Register
action creates the user by calling CreateAsync
on the _userManager
object (provided to AccountController
by dependency injection):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).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 Introduction to authorization in ASP.NET Core.The Login form is displayed when users select the Log in link or are redirected when accessing a page that requires authentication. When the user submits the form on the Login page, the
AccountController
Login
action is called.The
Login
action calls PasswordSignInAsync
on the _signInManager
object (provided to AccountController
by dependency injection).The base (
Controller
or PageModel
) class exposes a User
property. For example, User.Claims
can be enumerated to make authorization decisions.Log out
The Log out link invokes the
LogoutModel.OnPost
action.SignOutAsync clears the user's claims stored in a cookie.
Post is specified in the Pages/Shared/_LoginPartial.cshtml:
Clicking the Log out link calls the
LogOut
action.The preceding code calls the
_signInManager.SignOutAsync
method. The SignOutAsync
method clears the user's claims stored in a cookie.Test Identity
The default web project templates allow anonymous access to the home pages. To test Identity, add
[Authorize]
to the Privacy page.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:
- Examine the source of each page and step through the debugger.
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
languages | page_type | description | products | urlFragment | |
---|---|---|---|---|---|
sample | Learn how to add sign-in users to your web app, and how to call web APIs, either from Microsoft or your own. |
|
About this tutorial
Scope of this tutorial
In this tutorial, you will learn, incrementally, how to add sign-in users to your Web App, and how to call Web APIs, either from Microsoft or your own. Finally, you'll learn best practices and how to deploy your app to Azure
Note
We recommend that you right click on the picture above and open it in a new tab, or a new window. You'll see a clickable image:
- clicking on a metro/railway station will get you directly to the README.md for the corresponding part of the tutorial (some are still in progress)
- clicking on some of the connectors between stations will get you to an incremental README.md showing how to get from one part of the tutorial to the next (that's for instance the case for the Sign-in ... stations)
Details of the phases
- The first phase is to add sign-in users to your Web App leveraging the Microsoft identity platform for developers (formerly Azure AD v2.0). You'll learn how to use the ASP.NET Core OpenID Connect (OIDC) middleware itself leveraging Microsoft Identity Model extensions for .NET to protect your Web App.Depending on your business needs, you have the flexibility to decide which audience to sign-in to your application:
- If you are a Line of Business (LOB) developer, you'll want to sign-in users in your organization with their work or school accounts.
- If you are an ISV, you'll want to sign-in users in any organization, still with their work or school accounts.
- If you are an ISV targeting both organizations and individuals, you'll want to sign-in users with their work and school accounts or Microsoft personal accounts.
- LOB developer or ISV, if you target organizations (work or school accounts), you can also enable your application to sign-in users in national and sovereign clouds.
- If you are a business wanting to connect with your customers, or with small business partners, you might also want to sign-in users with their social identities using Microsoft Azure AD B2C.
- Finally, you'll want to let users sign-out of our application, or globally of the browser.
- Your Web App might maintain its own resources (in that case you have all you need so far), but it could also be that it calls Microsoft APIs.Learn how to update your Web App to call Microsoft Graph:
- Using the authorization code flow, initiated by ASP.NET Core, but completed by Microsoft Authentication Library for .NET (MSAL.NET)
- Learn how to customize the token cache serialization) with different technologies depending on your needs (in memory cache, Session token cache, SQL Cache, Redis Cache)
- Learn the [Planned] best practices and practices to avoid when calling an API.
- Your Web App might also want to call other Web APIs than Microsoft Graph.Learn how to call several Microsoft APIS. This also explains how to handle conditional access, incremental consent and claims challenge:
- the Azure Storage API. This is the opportunity to learn about incremental consent, and conditional access, and how to process them.
- the Azure ARM API. This is the opportunity to learn about admin consent.
Note that this phase, contrary to the others, requires you to have an Azure Subscription - Then you might yourself have written a Web API, and want to call it from your Web App.Learn how to update your Web App to call your own web api
- Once you know how to sign-in users and call Web APIs from your Web App, you might want to restrict part of the application depending on the user having a role in the application or belonging to a group. So far you've learnt how to add and process authentication. Now learn how to add authorization to your Web application, restricting part of it to users
- Chances are that you want to deploy your complete app to Azure. Learn how to do that, applying best practices:
- Changing the app registration to add more ReplyUris
- Using certificates instead of client secrets
- Possibly leveraging Managed identities to get these certificates from KeyVault
Reusable code for your Web Apps and Web APIs
In this tutorial, the complexities of ASP.NET Core OpenID connect middleware and MSAL.NET are encapsulated into a library project that you can reuse in your own code, to make it easier to build your Web Apps on top of Microsoft identity platform for developers: Microsoft.Identity.Web
Daemon apps - Out of scope
This tutorial only covers the case the Web App calls a Web API on behalf of a user. If you are interested in Web Apps calling Web APIs with their own identity (daemon Web Apps), please see Build a daemon Web App with Microsoft Identity platform for developers
How to run this sample
Pre-requisites
- Install .NET Core for Windows by following the instructions at dot.net/core, which will include Visual Studio 2017.
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant
- A user account in your Azure AD tenant, or a Microsoft personal account
Step 1: Clone or download this repository
From your shell or command line:
Given that the name of the sample is pretty long, that it has sub-folders and so are the name of the referenced NuGet pacakges, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.
- We recommend that you start by the first part 1. WebApp signs-in users with Microsoft identity (OIDC) where you will learn how to sign-in users within your own organization
- It's however possible to start at any phase of the tutorial as the full code is provided in each folder.
Community Help and Support
Use Stack Overflow to get support from the community.Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.Make sure that your questions or comments are tagged with [
msal
dotnet
].If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
Contributing
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
Other samples and documentation
- The documentation for the Microsoft identity platform is available from https://aka.ms/aadv2.
- Other samples for the Microsoft identity platform are available from https://aka.ms/aaddevsamplesv2.
- The conceptual documentation for MSAL.NET is available from https://aka.ms/msalnet.