ASP.NET Core - 身份驗證配置



本章將介紹如何安裝和配置身份驗證框架,這隻需要少量的工作。如果您使用 Visual Studio 建立一個新的 ASP.NET Core 應用程式,並選擇帶有設定為單個使用者帳戶的身份驗證的完整 Web 應用程式模板,則該新專案將包含為您設定的所有身份驗證框架元件。

Identity Configuration

我們從一個空專案開始。我們現在將從頭開始設定身份驗證框架,這是一種瞭解完整應用程式模板中所有元件的好方法,因為如果您沒有詳細地研究過所有程式碼,可能會令人困惑。

首先,我們需要安裝依賴項,即 **Microsoft.AspNet.Identity**。我們將繼續安裝 **Microsoft.AspNet.Identity.EntityFramework**,然後實現與 Entity Framework 協同工作的身份驗證框架。

  • 如果我們依賴 Identity.EntityFramework,則該包包含 Identity 包。

  • 如果您構建自己的資料儲存,則可以使用 Identity 包。

  • 安裝依賴項後,我們可以建立一個自定義 User 類,其中包含我們想要儲存的有關使用者的所有資訊。

  • 對於此應用程式,我們將繼承身份驗證框架提供的類,該類將為我們提供所有必需項,例如 Username 屬性和儲存雜湊密碼的位置。

ASP.NET Identity
  • 我們還需要修改我們的 **FirstAppDemoDbContext** 類以繼承自身份驗證框架的 **IdentityDbContext** 類。

  • IdentityDbContext 為我們提供了使用 Entity Framework 儲存使用者資訊所需的一切。一旦我們設定了 User 類和 **DbContext**,我們就需要使用 Startup 類的 **ConfigureServices** 方法將身份驗證服務配置到應用程式中。

  • 就像我們需要新增服務來支援 MVC 框架一樣,身份驗證框架也需要將服務新增到應用程式才能工作。

  • 這些服務包括 **UserStore** 服務和 **SignInManager** 服務。

  • 我們將把這些服務注入到我們的控制器中,以便在適當的時間建立使用者併發出 Cookie。

  • 最後,在啟動的 Configure 方法期間,我們需要新增身份驗證中介軟體。

  • 此中介軟體不僅有助於將 Cookie 轉換為使用者身份,而且還可以確保使用者不會看到帶有 401 響應的空頁面。

現在讓我們按照以下步驟操作。

**步驟 1** - 我們需要透過新增對身份驗證框架的依賴項來繼續。讓我們將 Microsoft.AspNet.Identity.EntityFramework 依賴項新增到 project.json 檔案中。這將包含我們需要的其他所有必要的身份驗證包。

{ 
   "version": "1.0.0-*", 
   "compilationOptions": { 
      "emitEntryPoint": true 
   },  
  
   "dependencies": { 
      "Microsoft.AspNet.Mvc":  "6.0.0-rc1-final", 
      "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", 
      "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", 
      "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", 
      "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", 
      "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", 
      "EntityFramework.Commands": "7.0.0-rc1-final", 
      "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final", 
      "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final" 
   },  
   
   "commands": { 
      "web": "Microsoft.AspNet.Server.Kestrel", 
      "ef": "EntityFramework.Commands" 
   },  
  
   "frameworks": { 
      "dnx451": { }, 
      "dnxcore50": { } 
   },  
   
   "exclude": [ 
      "wwwroot", 
      "node_modules" 
   ], 
    
   "publishExclude": [ 
      "**.user", 
      "**.vspscc" 
   ] 
} 

**步驟 2** - 儲存此檔案。Visual Studio 將恢復包,現在我們可以新增我們的 User 類了。讓我們透過右鍵單擊 Models 資料夾並選擇新增→類來新增 User 類。

Code and Class Options

將此類命名為 User 並單擊新增按鈕,如上圖所示。在此類中,您可以新增屬性以儲存您想要儲存的有關使用者的任何資訊。

**步驟 3** - 讓我們從身份驗證框架提供的類派生 User 類。它是 Identity.EntityFramework 名稱空間中的 IdentityUser 類。

using Microsoft.AspNet.Identity.EntityFramework; 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppDemo.Models { 
   public class User : IdentityUser { 
   } 
}

**步驟 4** - 讓我們現在轉到 IdentityUser,將游標放在該符號上,然後按 F12 以檢視 Visual Studio 的元資料檢視。

#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0,   

namespace Microsoft.AspNet.Identity.EntityFramework { 
   public class IdentityUser : IdentityUser<string> { 
      public IdentityUser(); 
      public IdentityUser(string userName); 
   } 
}

**步驟 5** - 您可以看到 IdentityUser 是從字串的 IdentityUser 派生的。您可以透過從 IdentityUser 派生並指定我們的泛型型別引數來更改主鍵的型別。您還可以使用理想情況下為整數值的主鍵儲存內容。

**步驟 6** - 讓我們現在將游標放在字串的 IdentityUser 上,然後再次按 F12 以轉到元資料檢視。

Identity User

您現在可以檢視預設情況下與使用者相關的所有資訊。這些資訊包括:

  • 我們在此應用程式中不會使用的欄位,但可以使用。

  • 身份驗證框架可以跟蹤特定使用者的失敗登入嘗試次數,並在一段時間後鎖定該帳戶。

  • 儲存 PasswordHash、PhoneNumber 的欄位。我們將使用的兩個重要欄位是 PasswordHash 和 UserName。

  • 我們還將隱式使用使用者的 primary key 和 ID 屬性。如果您需要查詢特定使用者,也可以使用該屬性。

**步驟 7** - 現在,我們需要確保 User 包含在我們的 DbContext 中。因此,讓我們開啟應用程式中擁有的 **FirstAppDemoDBContext**,並且不直接從 DBContext(內建的 Entity Framework 基類)派生它,現在我們需要從 IdentityDbContext 派生它。

using Microsoft.AspNet.Identity.EntityFramework; 
using Microsoft.Data.Entity;  

namespace FirstAppDemo.Models { 
   public class FirstAppDemoDbContext : IdentityDbContext<User> { 
      public DbSet<Employee> Employees { get; set; }  
      
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 
         optionsBuilder.UseSqlServer("Data Source = (localdb)\\MSSQLLocalDB;
            Initial Catalog = FirstAppDemo;Integrated Security = True;
            Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;
            ApplicationIntent = ReadWrite;MultiSubnetFailover = False"); 
      } 
   } 
}        

**步驟 8** - IdentityDbContext 類也在 Microsoft.AspNet.Identity.EntityFramework 名稱空間中,我們可以指定它應該儲存的使用者型別。這樣,我們新增到 User 類的任何其他欄位都會進入資料庫。

  • IdentityDbContext 帶來了額外的 DbSet,不僅用於儲存使用者,還用於儲存有關使用者角色和使用者宣告的資訊。

  • 我們的 User 類現在已準備就緒。我們的 FirstAppDemoDbContext 類已配置為與身份驗證框架協同工作。

  • 我們現在可以進入 Configure 和 ConfigureServices 來設定身份驗證框架。

**步驟 9** - 讓我們現在從 **ConfigureServices** 開始。除了我們的 MVC 服務和我們的 Entity Framework 服務外,我們還需要新增我們的身份驗證服務。這將新增身份驗證框架依賴於執行其工作的所有服務。

public void ConfigureServices(IServiceCollection services) { 
   services.AddMvc(); 
   
   services.AddEntityFramework() 
      .AddSqlServer() 
      .AddDbContext<FirstAppDemoDbContext>
      (option => option.UseSqlServer(Configuration["database:connection"]));  
      
   services.AddIdentity<User, IdentityRole>() 
      .AddEntityFrameworkStores<FirstAppDemoDbContext>(); 
}
  • AddIdentity 方法採用兩個泛型型別引數——使用者實體的型別和角色實體的型別。

  • 這兩個泛型型別引數是我們使用者的型別——我們剛剛建立的 User 類和我們想要使用的 Role 類。我們現在將使用內建的 IdentityRole。此類位於 EntityFramework 名稱空間中。

  • 當我們將 Entity Framework 與 Identity 一起使用時,我們還需要呼叫第二個方法——AddEntityFrameworkStores。

  • AddEntityFrameworkStores 方法將配置諸如 UserStore 之類的服務,該服務用於建立使用者並驗證其密碼。

**步驟 10** - 下面的兩行是我們配置應用程式服務的全部內容。

services.AddIdentity<User, IdentityRole>() 
   .AddEntityFrameworkStores<FirstAppDemoDbContext>();

**步驟 11** - 我們還需要新增中介軟體。我們插入中介軟體的位置很重要,因為如果我們過晚插入中介軟體,它將永遠沒有機會處理請求。

如果我們需要在我們的 MVC 控制器中進行授權檢查,我們需要在 MVC 框架之前插入身份驗證中介軟體,以確保成功處理 Cookie 和 401 錯誤。

public void Configure(IApplicationBuilder app) { 
   app.UseIISPlatformHandler();  
   
   app.UseDeveloperExceptionPage(); 
   app.UseRuntimeInfoPage();  
  
   app.UseFileServer();  
   
   app.UseIdentity(); 
   app.UseMvc(ConfigureRoute);  
   
   app.Run(async (context) => { 
      var msg = Configuration["message"]; 
      await context.Response.WriteAsync(msg); 
   });  
} 

**步驟 12** - 我們插入中介軟體的位置就是我們將新增身份驗證中介軟體的位置。以下是 Startup.cs 檔案的完整實現。

using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http;

using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration; 

using FirstAppDemo.Services; 
using Microsoft.AspNet.Routing; 
using System; 

using FirstAppDemo.Entities; 
using Microsoft.Data.Entity; 

using FirstAppDemo.Models; 
using Microsoft.AspNet.Identity.EntityFramework;  

namespace FirstAppDemo { 
   public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder() 
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      public IConfiguration Configuration { get; set; }  
        
      // This method gets called by the runtime.
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID = 398940 
      public void ConfigureServices(IServiceCollection services) { 
         services.AddMvc(); 
            services.AddEntityFramework() 
            .AddSqlServer() 
            .AddDbContext<FirstAppDemoDbContext>(option => 
            option.UseSqlServer(Configuration["database:connection"]));  
         
         services.AddIdentity<User, IdentityRole>() 
            .AddEntityFrameworkStores<FirstAppDemoDbContext>(); 
      }
      // This method gets called by the runtime.  
      // Use this method to configure the HTTP request pipeline. 
      public void Configure(IApplicationBuilder app) { 
         app.UseIISPlatformHandler();  
         app.UseDeveloperExceptionPage(); 
         app.UseRuntimeInfoPage();  
         app.UseFileServer();  
         app.UseIdentity(); 
         app.UseMvc(ConfigureRoute);  
         
         app.Run(async (context) => { 
            var msg = Configuration["message"]; 
            await context.Response.WriteAsync(msg); 
         }); 
      }  
      private void ConfigureRoute(IRouteBuilder routeBuilder) { 
         //Home/Index 
         routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); 
      }  
      // Entry point for the application. 
      public static void Main(string[] args) => WebApplication.Run<Startup>(args); 
   } 
}

**步驟 13** - 讓我們現在繼續構建應用程式。在下一章中,我們需要新增另一個 Entity Framework 遷移,以確保我們的 SQL Server 資料庫中包含身份驗證模式。

廣告
© . All rights reserved.