將驗證和 Identity 移轉至 ASP.NET Core

作者:Steve Smith

在上一篇文章中,我們已將設定從 ASP.NET MVC 專案移轉至 ASP.NET Core MVC。 在本文中,我們會移轉註冊、登入和使用者管理功能。

設定 Identity 和成員資格

在 ASP.NET MVC 中,驗證和身分識別功能是使用 Startup.Auth.csIdentityConfig.cs (位於 App_Start 資料夾) 中的 ASP.NET Identity 來設定。 在 ASP.NET Core MVC 中,這些功能是在 Startup.cs 中設定。

安裝下列 NuGet 套件:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Authentication.Cookies
  • Microsoft.EntityFrameworkCore.SqlServer

Startup.cs 中,更新 Startup.ConfigureServices 方法以使用 Entity Framework 和 Identity 服務:

public void ConfigureServices(IServiceCollection services)
{
    // Add EF services to the services container.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

     services.AddMvc();
}

此時,有兩種在上述程式碼中參考的類型,我們尚未從 ASP.NET MVC 專案移轉這兩種類型:ApplicationDbContextApplicationUser。 在 ASP.NET Core 專案中建立新的 Models 資料夾,並將對應至這些類型的兩個類別新增至其中。 您會在 /Models/IdentityModels.cs 中找到這些類別的 ASP.NET MVC 版本,但我們會在移轉的專案中為每個類別使用一個檔案,因為這樣更清楚。

ApplicationUser.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace NewMvcProject.Models
{
    public class ApplicationUser : IdentityUser
    {
    }
}

ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Data.Entity;

namespace NewMvcProject.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Core Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Core Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

ASP.NET Core MVC Starter Web 專案不會包含使用者的許多自訂,或 ApplicationDbContext。 移轉實際的應用程式時,您也需要移轉應用程式使用者和 DbContext 類別的所有自訂屬性和方法,以及應用程式使用的任何其他模型類別。 例如,如果您的 DbContext 具有 DbSet<Album>,則需要移轉 Album 類別。

這些檔案就位後,可以藉由更新 Startup.cs 陳述式來編譯 using 檔案:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

我們的應用程式現在已準備好支援驗證和 Identity 服務。 其只需要將這些功能公開給使用者即可。

移轉註冊和登入邏輯

透過針對應用程式設定的 Identity 服務,以及使用 Entity Framework 和 SQL Server 所設定的資料存取,我們準備好將註冊和登入的支援新增至應用程式。 回想一下,稍早在移轉過程中,我們已註解化 _Layout.cshtml_LoginPartial 的參考。 現在是時候回到該程式碼、取消註解,並加入必要的控制器和檢視,以支援登入功能。

取消註解 _Layout.cshtml 中的 @Html.Partial 行:

      <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>
    @*@Html.Partial("_LoginPartial")*@
  </div>
</div>

現在,將稱為 _LoginPartial 的新 Razor 檢視新增至 Views/Shared 資料夾:

使用下列程式碼更新 _LoginPartial.cshtml (取代其所有內容):

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
            </li>
        </ul>
    </form>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
        <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
    </ul>
}

此時,您應該能夠在瀏覽器中重新整理網站。

摘要

ASP.NET Core 引進了 ASP.NET Identity 功能的變更。 在本文中,您已了解如何將 ASP.NET Identity 的驗證和使用者管理功能移轉至 ASP.NET Core。