asp.net core系列 46 Identity介紹
一. Identity 介紹
ASP.NET Core Identity是一個會員系統,可為ASP.NET Core應用程式添加登入功能。可以使用SQL Server資料庫配置身份以存儲使用者名,密碼和配置檔案資料。或者,可以使用另一個持久性存儲,例如,Azure表存儲。下面學習如何使用Identity注冊,登入以及基架辨別。
1.1 Identity搭建示範
下面使用vs 2017來示範:
1.選擇“檔案” > “建立” > “項目”。
2.選擇“ASP.NET Core Web應用程式”。 将項目命名WebAppIdentityDemo具有項目下載下傳相同的命名空間。 單擊 “确定”。
3.選擇 ASP.NET Core Web MVC應用程式,然後選擇更改身份驗證。
4.選擇單個使用者帳戶然後單擊确定。
生成的項目包含了Identity會員系統,目錄結構如下所示,生成後的目錄結構有疑惑,怎麼沒看見Identity會員系統相關的model, Controller,cshtml等檔案,繼續往下了解。
(1) 修改連接配接字元串
找到appsettings.json檔案,修改ConnectionStrings的資料庫連接配接字元串, 預設是連接配接本機sql server資料庫,我改成了連接配接遠端資料庫。
"ConnectionStrings": {
"DefaultConnection": "Data Source = 172.168.16.75;Initial Catalog =IdentityDB; User ID = hsr;Password =js*2015;"
},
(2) 基于生成的遷移代碼,同步到資料庫
PM> Update-Database
(3) 配置Identity服務
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
(4) 确認調用UseAuthentication中間件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
(5) 啟動程式,首頁提供了注冊,登入的連結
注冊成功後/Identity/Account/Register,在資料庫中AspNetUsers表會新增一條資料(密碼:Asp.netCore123)。注冊成功後,說明資料庫連接配接沒有問題,會跳到登入頁Identity/Account/Login
雖然沒有看到Identity會員系統相關檔案,其實已經内置由Razor類庫提供。Identity Razor類庫使用該Identity Areas公開端點。例如:
/Identity/Account/Login
/Identity/Account/Logout
/Identity/Account/Manage
二. 基架辨別(Scaffold Identity )
ASP.NET Core 2.1 及更高版本提供了ASP.NET Core Identity作為Razor 類庫。 包含Identity的應用程式可以應用基架,來有選擇地添加包含在Identity Razor 類庫 (RCL) 的源代碼。 建議生成源代碼,以便修改代碼和更改行為(根據開發需求擴充Identity)。 例如,可以訓示基架生成在注冊過程中使用的代碼。 生成的代碼優先于辨別 RCL 中的相同代碼。 若要擷取的使用者界面的完全控制,并且使用預設 RCL,等下參考2.2。
2.1 使用Scaffold Identity 授權到MVC 項目
1.從解決方案資料總管,右鍵單擊該項目 >添加 > 新基架項。
2.從左窗格添加基架對話框中,選擇辨別 > 添加。
3.在中ADD 辨別添加對話框中,選擇所需的選項。
下面使用現有的資料上下文,選擇所有檔案,以便後面重寫,如下所示。
生成需要重寫的檔案後,如下所示(可以比對上圖1.1的Areas目錄),注意生成的是razor page 檔案,不是MVC視圖控制器。之前上面的疑惑解除了。
2.2 建立完整的Identity UI 源
上面2.1中運作Scaffold Identity,保持了對Identity UI的完全控制。以下突出顯示的代碼顯示預設Identity UI 替換Identity在 ASP.NET Core 2.1 web 應用的更改。 需要執行此操作以具有完全控制權限的Identity UI。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
//services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
//services.ConfigureApplicationCookie(options =>
//{
// // Cookie settings
// options.Cookie.HttpOnly = true;
// options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
// options.LoginPath = "/Identity/Account/Login";
// options.AccessDeniedPath = "/Identity/Account/AccessDenied";
// options.SlidingExpiration = true;
//});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
// services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
}
選擇修改Login.cshtml檔案,在裡面随變加點标記xxxx, 運作顯示成功,以後就可以自定義樣式布局和擴充權限功能。
參考文獻
ASP.NET Core 上的Identity簡介
ASP.NET Core 項目中的scaffold-identity
posted on 2019-03-21 17:00 花陰偷移 閱讀(...) 評論(...) 編輯 收藏