ASP.NET Identity 簡介Introduction to ASP.NET Identity

ASP.NET 成員資格系統被引進 ASP.NET 2.0 後在 2005 中,而由於則已有許多變更 web 應用程式通常會處理驗證和授權方式。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 身分識別是成員資格系統應該是什麼當您在建立 web、 手機或平板電腦的現代化應用程式的全新觀點。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.

背景:在 ASP.NET 中的成員資格Background: Membership in ASP.NET

ASP.NET 成員資格ASP.NET Membership

ASP.NET 成員資格用來解決常用的 2005,因為它牽涉到表單驗證,以及使用者名稱、 密碼和設定檔資料的 SQL Server 資料庫的站台成員資格需求。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. 目前沒有更廣泛的 web 應用程式,資料儲存體選項,而且大部分的開發人員想要啟用自己的網站使用社交識別提供者驗證和授權功能。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. ASP.NET 成員資格的設計限制進行這項轉換不容易:The limitations of ASP.NET Membership's design make this transition difficult:

  • 資料庫結構描述專為 SQL Server,您無法變更它。The database schema was designed for SQL Server and you can't change it. 您可以新增設定檔資訊,但其他的資料封裝至不同的資料表,很難存取的設定檔提供者 API 透過任何方式除外。You can add profile information, but the additional data is packed into a different table, which makes it difficult to access by any means except through the Profile Provider API.
  • 提供者系統可讓您變更 支援的資料存放區,但系統針對假設適用於關聯式資料庫設計。The provider system enables you to change the backing data store, but the system is designed around assumptions appropriate for a relational database. 您可以撰寫的提供者,將成員資格資訊儲存在非關聯式儲存體機制,例如 Azure 儲存體資料表,但是,您必須解決關聯式的設計,撰寫太多程式碼和許多System.NotImplementedException不的方法的例外狀況適用於 NoSQL 資料庫。You can write a provider to store membership information in a non-relational storage mechanism, such as Azure Storage Tables, but then you have to work around the relational design by writing much code and a lot of System.NotImplementedException exceptions for methods that don't apply to NoSQL databases.
  • 由於記錄輸入/記錄檔外的功能根據表單驗證,不能使用成員資格系統OWINSince the log-in/log-out functionality is based on Forms Authentication, the membership system can't use OWIN. OWIN 包含中介軟體元件進行驗證,包括支援登入使用外部識別提供者 (例如 Microsoft 帳戶、 Facebook、 Google、 Twitter),並登入使用組織帳戶,從內部部署 Active Directory 或Azure Active Directory。OWIN includes middleware components for authentication, including support for log-ins using external identity providers (like Microsoft Accounts, Facebook, Google, Twitter), and log-ins using organizational accounts from on-premises Active Directory or Azure Active Directory. OWIN 也包含對 OAuth 2.0 JWT,CORS 支援。OWIN also includes support for OAuth 2.0, JWT and CORS.

ASP.NET 簡易成員資格ASP.NET Simple Membership

ASP.NET 簡易成員資格ASP.NET Web Pages 做為成員資格系統所開發。ASP.NET simple membership was developed as a membership system for ASP.NET Web Pages. 使用 WebMatrix 和 Visual Studio 2010 SP1 釋出。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.

簡單成員資格未讓您更輕鬆地自訂使用者設定檔資訊,但它仍共用其他問題與 ASP.NET 成員資格,而且具有一些限制: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:

  • 真的很難保存非關聯式存放區中的成員資格系統資料。It was hard to persist membership system data in a non-relational store.
  • 您無法搭配 OWIN 使用它。You can't use it with OWIN.
  • 它不適用於現有的 ASP.NET 成員資格提供者,而且無法擴充。It doesn't work well with existing ASP.NET Membership providers, and it's not extensible.

ASP.NET Universal ProvidersASP.NET Universal Providers

ASP.NET Universal Providers所開發,讓保存 Azure SQL Database,而且它們也適用於 SQL Server Compact 在 Microsoft 中的成員資格資訊。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. 通用的提供者已根據 Entity Framework Code First,這表示通用提供者可用來保存任何 EF 所支援的存放區中的資料。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.

Universal Providers ASP.NET 成員資格基礎結構之上,因此它們仍會帶 SqlMembership 提供者相同的限制。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 sign-in and sign-out functionality.

ASP.NET IdentityASP.NET Identity

成員資格的方式在 ASP.NET 中的劇本已發展多年來,來自客戶的意見回應的 「 ASP.NET 團隊有獲益良多。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 sign in by entering a user name and password that they have registered in your own application is no longer valid. Web 已經成為其他社交。The web has become more social. 使用者透過社交管道,例如 Facebook、 Twitter 和其他社交網站的即時與彼此互動。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 sign in with their social identities so that they can have a rich experience on their web sites. 現代的成員資格系統必須啟用重新導向以登入來驗證提供者,例如 Facebook、 Twitter 和其他項目。A modern membership system must enable redirection-based log-ins to authentication providers such as Facebook, Twitter, and others.

為 web 開發演變,因此未 web 開發的模式。As web development evolved, so did the patterns of web development. 單元測試的應用程式程式碼成為應用程式開發人員的核心考量。Unit testing of application code became a core concern for application developers. 在 2008 ASP.NET 會新增模型-檢視-控制器 (MVC) 模式,部分可協助開發人員建置單元測試的 ASP.NET 應用程式為基礎的新架構。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.

考慮這些變更的 web 應用程式開發中,ASP.NET 身分識別開發人員在開發下列目標:Considering these changes in web application development, ASP.NET Identity was developed with the following goals:

  • 一個 ASP.NET 身分識別系統One ASP.NET Identity system

    • 可以與所有的 ASP.NET 架構,例如 ASP.NET MVC、 Web Form、 Web 頁面、 Web API,以及 SignalR 使用 ASP.NET 身分識別。ASP.NET Identity can be used with all of the ASP.NET frameworks, such as ASP.NET MVC, Web Forms, Web Pages, Web API, and SignalR.
    • 當您在建立 web、 電話、 存放區或混合式應用程式,可以使用 ASP.NET 身分識別。ASP.NET Identity can be used when you are building web, phone, store, or hybrid applications.
  • 簡易的插入使用者相關的設定檔資料Ease of plugging in profile data about the user

    • 您可以控制使用者與設定檔資訊的結構描述。You have control over the schema of user and profile information. 比方說,您可以輕鬆地啟用系統所儲存的應用程式中註冊帳戶時,輸入使用者的出生日期。For example, you can easily enable the system to store birth dates entered by users when they register an account in your application.
  • 持續性控制項Persistence control

    • 根據預設,ASP.NET 身分識別系統會將所有的使用者資訊儲存在資料庫中。By default, the ASP.NET Identity system stores all the user information in a database. ASP.NET 身分識別會使用 Entity Framework Code First 來實作所有持續性機制。ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.
    • 由於您控制的資料庫結構描述、 常見的工作,例如變更資料表名稱或變更主索引鍵的資料型別很容易做到。Since you control the database schema, common tasks such as changing table names or changing the data type of primary keys is simple to do.
    • 很容易插入不同的儲存機制,例如 SharePoint、 Azure 儲存體表格服務、 NoSQL 資料庫 」 等,而不需擲回System.NotImplementedExceptions例外狀況。It's easy to plug in different storage mechanisms such as SharePoint, Azure Storage Table Service, NoSQL databases, etc., without having to throw System.NotImplementedExceptions exceptions.
  • 單元測試Unit testability

    • ASP.NET 身分識別可讓 web 應用程式更多單元測試。ASP.NET Identity makes the web application more unit testable. 您可以撰寫單元測試,您的應用程式使用 ASP.NET 身分識別的組件。You can write unit tests for the parts of your application that use ASP.NET Identity.
  • 角色提供者Role provider

    • 沒有角色提供者可讓您限制對您的應用程式的組件的角色存取。There is a role provider which lets you restrict access to parts of your application by roles. 您可以輕鬆地建立角色,例如"Admin",並將使用者新增至角色。You can easily create roles such as "Admin" and add users to roles.
  • 宣告式Claims Based

    • ASP.NET 身分識別支援宣告式的驗證,而使用者的身分識別都代表一組宣告。ASP.NET Identity supports claims-based authentication, where the user's identity is represented as a set of claims. 宣告讓開發人員可在描述使用者的身分識別,比角色,可讓更多易懂。Claims allow developers to be a lot more expressive in describing a user's identity than roles allow. 角色成員資格是只是布林值 (成員或非成員),而宣告可以包含使用者的身分識別與成員資格的豐富資訊。Whereas role membership is just a boolean (member or non-member), a claim can include rich information about the user's identity and membership.
  • 社交登入提供者Social Login Providers

    • 可以輕鬆地將社交登入等的 Microsoft 帳戶、 Facebook、 Twitter、 Google 和其他人新增至您的應用程式,並將使用者專屬資料儲存在您的應用程式。You can easily add social log-ins such as Microsoft Account, Facebook, Twitter, Google, and others to your application, and store the user-specific data in your application.
  • OWIN 整合OWIN Integration

    • ASP.NET 驗證現在根據可用在以 OWIN 為基礎的任何主機的 OWIN 中介軟體。ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. 在 System.Web,ASP.NET 身分識別並沒有任何相依性。ASP.NET Identity does not have any dependency on System.Web. 它是完全相容的 OWIN 架構,並可以用於任何裝載的 OWIN 應用程式。It is a fully compliant OWIN framework and can be used in any OWIN hosted application.
    • ASP.NET Identity 中/記錄檔-登出的使用者在網站上使用 OWIN 驗證。ASP.NET Identity uses OWIN Authentication for log-in/log-out of users in the web site. 這表示,而不是使用 FormsAuthentication 產生 cookie,應用程式使用 OWIN CookieAuthentication 若要這麼做。This means that instead of using FormsAuthentication to generate the cookie, the application uses OWIN CookieAuthentication to do that.
  • NuGet 套件NuGet package

    • ASP.NET 身分識別,則會重新分配以 NuGet 套件安裝隨附於 Visual Studio 2017 的 ASP.NET MVC、 Web Form 和 Web API 範本中。ASP.NET Identity is redistributed as a NuGet package which is installed in the ASP.NET MVC, Web Forms and Web API templates that ship with Visual Studio 2017. 您可以從 NuGet 資源庫下載這個 NuGet 封裝。You can download this NuGet package from the NuGet gallery.
    • 釋出 ASP.NET 身分識別為 NuGet 套件可讓 ASP.NET 小組的新功能及 bug 修正,逐一查看,並以敏捷的方式提供這些開發人員更輕鬆。Releasing ASP.NET Identity as a NuGet package makes it easier for the ASP.NET team to iterate on new features and bug fixes, and deliver these to developers in an agile manner.

開始使用 ASP.NET IdentityGet started with ASP.NET Identity

ASP.NET 身分識別可在 Visual Studio 2017 專案範本的 ASP.NET MVC、 Web Form、 Web API 和 SPA 之間。ASP.NET Identity is used in the Visual Studio 2017 project templates for ASP.NET MVC, Web Forms, Web API and SPA. 在本逐步解說中,我們將說明的專案範本如何使用 ASP.NET 身分識別來將功能新增至註冊、 登入和登出使用者。In this walkthrough, we'll illustrate how the project templates use ASP.NET Identity to add functionality to register, sign in and sign out a user.

使用下列程序來實作 ASP.NET 身分識別。ASP.NET Identity is implemented using the following procedure. 本文的目的是讓您的 ASP.NET 身分識別; 的高階概觀您可以遵循逐步或只是讀取的詳細資料。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. 如需建立使用 ASP.NET 身分識別,包括新增使用者、 角色和設定檔資訊,請使用新的 API 應用程式的詳細指示,請參閱本文結尾 「 後續步驟 」 一節。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. 建立 ASP.NET MVC 應用程式使用個別的帳戶。Create an ASP.NET MVC application with Individual Accounts. 您可以使用 ASP.NET MVC、 Web Form、 Web API 等等 SignalR 的 ASP.NET 身分識別。在本文中,我們將開始使用 ASP.NET MVC 應用程式。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. 建立的專案會包含下列三個封裝,ASP.NET 身分識別。The created project contains the following three packages for ASP.NET Identity.

    • Microsoft.AspNet.Identity.EntityFramework
      此套件有 Entity Framework 實作會將 ASP.NET Identity 的資料和 SQL server 的結構描述保存 ASP.NET 身分識別。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
      此套件有 ASP.NET Identity 的核心介面。This package has the core interfaces for ASP.NET Identity. 此套件可用來撰寫 ASP.NET 身分識別的目標不同的持續性儲存例如 Azure 資料表儲存體,NoSQL 資料庫等實作。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
      此套件包含用來在 ASP.NET 應用程式中插入 OWIN 驗證中使用 ASP.NET Identity 的功能。This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. 您將登功能新增至您的應用程式和呼叫 OWIN 的 Cookie 驗證中介軟體以產生 cookie 時,會使用這項目。This is used when you add sign 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 that collects the user name and password.

    當使用者選取註冊 按鈕,Register帳戶控制器的動作會建立使用者,方法是呼叫 ASP.NET 身分識別 API,以反白顯示如下:When the user selects the Register button, the Register action of the Account controller creates the user by calling the ASP.NET Identity API, as highlighted below:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    }
    
  4. 登入。Sign in.
    如果已成功建立使用者,她會登入SignInAsync方法。If the user was successfully created, she is signed in by the SignInAsync method.

     [HttpPost]
     [AllowAnonymous]
     [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                 await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                        
                 // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                 // Send an email with this link
                 // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                 // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                 // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
    
                 return RedirectToAction("Index", "Home");
             }
             AddErrors(result);
         }
    
        // If we got this far, something failed, redisplay form
         return View(model);
     }
    

    SignInManager.SignInAsync方法會產生ClaimsIdentityThe SignInManager.SignInAsync method generates a ClaimsIdentity. 由於 ASP.NET 身分識別和 OWIN Cookie 驗證以宣告為基礎的系統,framework 就會需要應用程式來產生使用者的 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 有使用者,例如使用者屬於何種角色的所有宣告的相關資訊。ClaimsIdentity has information about all the claims for the user, such as what roles the user belongs to.

  5. 登出。Log off.
    選取 登出呼叫登出動作帳戶控制器中的連結。Select the Log off link to call the LogOff action in the account controller.

    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Index", "Home");
    }
    

    反白顯示上述的程式碼顯示 OWINAuthenticationManager.SignOut方法。The highlighted code above shows the OWIN AuthenticationManager.SignOut method. 這相當於FormsAuthentication.SignOut所使用的方法FormsAuthentication在 Web Form 中的模組。This is analogous to FormsAuthentication.SignOut method used by the FormsAuthentication module in Web Forms.

ASP.NET 身分識別的元件Components of ASP.NET Identity

下圖顯示 ASP.NET 身分識別系統的元件 (上,選取或將它放大圖表上)。The diagram below shows the components of the ASP.NET Identity system (select on this or on the diagram to enlarge it). 以綠色的封裝是由 ASP.NET 身分識別系統所組成。The packages in green make up the ASP.NET Identity system. 所有其他套件是使用 ASP.NET 身分識別系統在 ASP.NET 應用程式時所需的相依性。All the other packages are dependencies which are needed to use the ASP.NET Identity system in ASP.NET applications.

以下是先前未提及的 NuGet 套件的簡短描述:The following is a brief description of the NuGet packages not mentioned previously:

  • Microsoft.Owin.Security.CookiesMicrosoft.Owin.Security.Cookies
    中介軟體,可讓應用程式使用 cookie 型驗證,類似於 ASP。NET 的表單驗證。Middleware that enables an application to use cookie based authentication, similar to ASP.NET's Forms Authentication.
  • EntityFrameworkEntityFramework
    Entity Framework 是 Microsoft 的關聯式資料庫的建議的資料存取技術。Entity Framework is Microsoft's recommended data access technology for relational databases.

從成員資格移轉至 ASP.NET IdentityMigrating from Membership to ASP.NET Identity

我們希望能很快就提供移轉您現有的應用程式到新的 ASP.NET 身分識別系統中使用 ASP.NET 成員資格或簡單的成員資格的指引。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