"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Introduction to ASP.NET Identity

by Jon Galloway, Pranav Rastogi, Rick Anderson, Tom Dykstra

The ASP.NET membership system was introduced with ASP.NET 2.0 back in 2005, and since then there have been many changes in the ways web applications typically handle authentication and authorization. ASP.NET Identity is a fresh look at what the membership system should be when you are building modern applications for the web, phone, or tablet.

This article was written by Pranav Rastogi ([@rustd](https://twitter.com/rustd)), Jon Galloway ([@jongalloway](https://twitter.com/jongalloway)), Tom Dykstra, and Rick Anderson ([@RickAndMSFT](https://twitter.com/#!/RickAndMSFT) ).

Background: Membership in ASP.NET

ASP.NET Membership

ASP.NET Membership was designed to solve site membership requirements that were common in 2005, which involved Forms Authentication, and a SQL Server database for user names, passwords, and profile data. Today there is a much broader array of data storage options for web applications, and most developers want to enable their sites to use social identity providers for authentication and authorization functionality. The limitations of ASP.NET Membership’s design make this transition difficult:

ASP.NET Simple Membership

ASP.NET simple membership was developed as a membership system for ASP.NET Web Pages. It was released with WebMatrix and Visual Studio 2010 SP1. The goal of Simple Membership was to make it easy to add membership functionality to a Web Pages application.

Simple Membership did make it easier to customize user profile information, but it still shares the other problems with ASP.NET Membership, and it has some limitations:

ASP.NET Universal Providers

ASP.NET Universal Providers were developed to make it possible to persist membership information in Microsoft Azure SQL Database, and they also work with SQL Server Compact. The Universal Providers were built on Entity Framework Code First, which means that the Universal Providers can be used to persist data in any store supported by EF. With the Universal Providers, the database schema was cleaned up quite a lot as well.

The Universal Providers are built on the ASP.NET Membership infrastructure, so they still carry the same limitations as the SqlMembership Provider. That is, they were designed for relational databases and it’s hard to customize profile and user information. These providers also still use Forms Authentication for log-in and log-out functionality.

ASP.NET Identity

As the membership story in ASP.NET has evolved over the years, the ASP.NET team has learned a lot from feedback from customers.

The assumption that users will log in by entering a user name and password that they have registered in your own application is no longer valid. The web has become more social. Users are interacting with each other in real time through social channels such as Facebook, Twitter, and other social web sites. Developers want users to be able to log in with their social identities so that they can have a rich experience on their web sites. A modern membership system must enable redirection-based log-ins to authentication providers such as Facebook, Twitter, and others.

As web development evolved, so did the patterns of web development. Unit testing of application code became a core concern for application developers. In 2008 ASP.NET added a new framework based on the Model-View-Controller (MVC) pattern, in part to help developers build unit testable ASP.NET applications. Developers who wanted to unit test their application logic also wanted to be able to do that with the membership system.

Considering these changes in web application development, ASP.NET Identity was developed with the following goals:

Getting started with ASP.NET Identity

ASP.NET Identity is used in the Visual Studio 2013 project templates for ASP.NET MVC, Web Forms, Web API and SPA. In this walkthrough, we’ll illustrate how the project templates use ASP.NET Identity to add functionality to register, log in and log out a user.

ASP.NET Identity is implemented using the following procedure. The purpose of this article is to give you a high level overview of ASP.NET Identity; you can follow it step by step or just read the details. For more detailed instructions on creating apps using ASP.NET Identity, including using the new API to add users, roles and profile information, see the Next Steps section at the end of this article.

  1. Create an ASP.NET MVC application with Individual Accounts. You can use ASP.NET Identity in ASP.NET MVC, Web Forms, Web API, SignalR etc. In this article we will start with an ASP.NET MVC application.

  2. The created project contains the following three packages for ASP.NET Identity.

    • Microsoft.AspNet.Identity.EntityFramework
      This package has the Entity Framework implementation of ASP.NET Identity which will persist the ASP.NET Identity data and schema to SQL Server.
    • Microsoft.AspNet.Identity.Core
      This package has the core interfaces for ASP.NET Identity. This package can be used to write an implementation for ASP.NET Identity that targets different persistence stores such as Azure Table Storage, NoSQL databases etc.
    • Microsoft.AspNet.Identity.OWIN
      This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add log in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.
  3. Creating a user.
    Launch the application and then click on the Register link to create a user. The following image shows the Register page which collects the user name and password.

When the user clicks the Register button, the Register action of the Account controller creates the user by calling the ASP.NET Identity API, as highlighted below:

[!code-csharpMain]
   1:  [HttpPost]
   2:  [AllowAnonymous]
   3:  [ValidateAntiForgeryToken]
   4:  public async Task<ActionResult> Register(RegisterViewModel model)
   5:  {
   6:      if (ModelState.IsValid)
   7:      {
   8:          var user = new ApplicationUser() { UserName = model.UserName };
   9:          var result = await UserManager.CreateAsync(user, model.Password);
  10:          if (result.Succeeded)
  11:          {
  12:              await SignInAsync(user, isPersistent: false);
  13:              return RedirectToAction("Index", "Home");
  14:          }
  15:          else
  16:          {
  17:              AddErrors(result);
  18:          }
  19:      }
  20:   
  21:      // If we got this far, something failed, redisplay form
  22:      return View(model);
  23:  }
  1. Log in.
    If the user was successfully created, she is logged in by the SignInAsync method.

    [!code-csharpMain]

       1:  [HttpPost]
       2:  [AllowAnonymous]
       3:  [ValidateAntiForgeryToken]
       4:  public async Task<ActionResult> Register(RegisterViewModel model)
       5:  {
       6:      if (ModelState.IsValid)
       7:      {
       8:          var user = new ApplicationUser() { UserName = model.UserName };
       9:          var result = await UserManager.CreateAsync(user, model.Password);
      10:          if (result.Succeeded)
      11:          {
      12:              await SignInAsync(user, isPersistent: false);
      13:              return RedirectToAction("Index", "Home");
      14:          }
      15:          else
      16:          {
      17:              AddErrors(result);
      18:          }
      19:      }
      20:   
      21:      // If we got this far, something failed, redisplay form
      22:      return View(model);
      23:  }

    [!code-csharpMain]

       1:  private async Task SignInAsync(ApplicationUser user, bool isPersistent)
       2:  {
       3:      AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
       4:   
       5:      var identity = await UserManager.CreateIdentityAsync(
       6:         user, DefaultAuthenticationTypes.ApplicationCookie);
       7:   
       8:      AuthenticationManager.SignIn(
       9:         new AuthenticationProperties() { 
      10:            IsPersistent = isPersistent 
      11:         }, identity);
      12:  }

The highlighted code above in the SignInAsync method generates a ClaimsIdentity. Since ASP.NET Identity and OWIN Cookie Authentication are claims-based system, the framework requires the app to generate a ClaimsIdentity for the user. ClaimsIdentity has information about all the claims for the user, such as what roles the user belongs to. You can also add more claims for the user at this stage.

The highlighted code below in the SignInAsync method signs in the user by using the AuthenticationManager from OWIN and calling SignIn and passing in the ClaimsIdentity.

[!code-csharpMain]
   1:  private async Task SignInAsync(ApplicationUser user, bool isPersistent)
   2:  {
   3:      AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
   4:   
   5:      var identity = await UserManager.CreateIdentityAsync(
   6:         user, DefaultAuthenticationTypes.ApplicationCookie);
   7:   
   8:      AuthenticationManager.SignIn(
   9:         new AuthenticationProperties() { 
  10:            IsPersistent = isPersistent 
  11:         }, identity);
  12:  }
  1. Log off.
    Clicking the Log off link calls the LogOff action in the account controller.

    [!code-csharpMain]

       1:  // POST: /Account/LogOff
       2:  [HttpPost]
       3:  [ValidateAntiForgeryToken]
       4:  public ActionResult LogOff()
       5:  {
       6:      AuthenticationManager.SignOut();
       7:      return RedirectToAction("Index", "Home");
       8:  }

The highlighted code above shows the OWIN AuthenticationManager.SignOut method. This is analogous to FormsAuthentication.SignOut method used by the FormsAuthentication module in Web Forms.

Components of ASP.NET Identity

The diagram below shows the components of the ASP.NET Identity system (click on this or on the diagram to enlarge it). The packages in green make up the ASP.NET Identity system. All the other packages are dependencies which are needed to use the ASP.NET Identity system in ASP.NET applications.

The following is a brief description of the NuGet packages not mentioned previously:

Migrating from Membership to ASP.NET Identity

We hope to soon provide guidance on migrating your existing apps that use ASP.NET Membership or Simple Membership to the new ASP.NET Identity system.

Next Steps



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/identity/overview/getting-started/introduction-to-aspnet-identity.htm
< THANKS ME>