從頭開始使用 ASP.NET Core 自訂身分驗證登入功能

在建立 ASP.NET Core MVC 專案時把驗證類型選擇「個別帳戶」,就完成使用者身份驗證(會員)功能的實作了

到目前為止還沒寫一行程式碼,但是基本的註冊、登入登出功能都有了

只是該如何調整頁面呢?搜尋「Log in」,竟然一個符合的單字都沒有!
原來從 ASP.NET Core 2.1 開始, .NET 就把基礎的身份認證功能包含在 Microsoft.AspNetCore.Identity.UI 和 Microsoft.AspNetCore.Identity.EntityFrameworkCore 的 DLL 中,在建立專案時就自動幫我們作完基本的工作了。

修改註冊密碼規則

執行後第一件事情就是註冊看看,預設註冊時密碼需要 6 個字元以上、包含英文大小寫、包含特殊符號,如果想要更改這些設定值,只要在 Program.cs 使用下面的身份選項 調整即可:
	
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.Configure<IdentityOptions>(options =>
{
    // 變更預設密碼設定
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;
});

builder.Services.AddControllersWithViews();

var app = builder.Build();
    

連接資料庫

如果使用時出現下列錯誤
  
A database operation failed while processing the request.

SqlException: Cannot open database "aspnet-WebApplicationIdentityTest" requested by the login. The login failed. Login failed for user 'ruyut\ruyut'.



代表資料庫中可能還沒有需要的資料表內容,可以使用 .NET CLI 自動將預設的資料庫和資料表內容新增進去
	
dotnet ef database update
    

註:執行指令時需要停止 ASP.NET Core 網站

自訂登入頁面

在方案總管中,對著專案點選滑鼠右鍵 > 加入 > 新增 Scaffold 項目

選擇「識別」,點選「加入」

等待大約 1 分鐘

勾選「Account\Login」,並將「資料內容類別」選擇 ApplicationDbContext (應該只會有一個選項),點選「新增」

如果出現錯誤,請檢查程式是不是還在執行中沒有關閉,關掉再試一次即可

剛剛的步驟增加了 5 個檔案

透過更改 Login.cshtml 檔案,就可以自訂內容了!



參考資料:
Introduction to Identity on ASP.NET Core

留言