隨著技術(shù)的發(fā)展,ASP.NET Core MVC也推出了好長時間,經(jīng)過不斷的版本更新迭代,已經(jīng)越來越完善,本系列文章主要講解ASP.NET Core MVC開發(fā)B/S系統(tǒng)過程中所涉及到的相關(guān)內(nèi)容,適用于初學(xué)者,在校畢業(yè)生,或其他想從事ASP.NET Core MVC 系統(tǒng)開發(fā)的人員。
經(jīng)過前幾篇文章的講解,初步了解ASP.NET Core MVC項目創(chuàng)建,啟動運(yùn)行,以及命名約定,創(chuàng)建控制器,視圖,模型,接收參數(shù),傳遞數(shù)據(jù)ViewData,ViewBag,路由,頁面布局,wwwroot和客戶端庫,Razor語法,EnityFrameworkCore與數(shù)據(jù)庫,HttpContext,Request,Response,Session,序列化,文件上傳,自動映射,Html輔助標(biāo)簽,模型校驗,鑒權(quán)、授權(quán)基礎(chǔ)等內(nèi)容,今天繼續(xù)講解ASP.NET Core MVC 中等Identity入門相關(guān)內(nèi)容,僅供學(xué)習(xí)分享使用。
什么是Identity?
ASP.NET Core Identity是用于構(gòu)建ASP.NET Core Web應(yīng)用程序的身份認(rèn)證系統(tǒng),包括用戶數(shù)據(jù),用戶身份以及注冊登錄信息數(shù)據(jù)存儲,可以讓您的應(yīng)用擁有登錄功能以及持續(xù)化存儲登錄用戶相關(guān)數(shù)據(jù)。
ASP.NET Core Identity:
-
一個 API,它支持用戶界面 (UI) 登錄功能。
-
管理用戶、密碼、配置文件數(shù)據(jù)、角色、聲明、令牌、電子郵件確認(rèn)等等。
用戶可使用存儲在 Identity 中的登錄信息創(chuàng)建帳戶,或者可使用外部登錄提供程序。支持的外部登錄提供程序包括 Facebook、Google、Microsoft 帳戶和 Twitter。
Identity 通常使用 SQL Server 數(shù)據(jù)庫進(jìn)行配置,以存儲用戶名、密碼和配置文件數(shù)據(jù)?;蛘撸墒褂闷渌志眯源鎯?,例如 Azure 表存儲。
在本主題中,你將學(xué)習(xí)Identity的注冊,登錄,登出等相關(guān)應(yīng)用。
?
Identity應(yīng)用步驟
?1. 通過模板創(chuàng)建項目
選擇模板【ASP.NET Core Web應(yīng)用(模型-視圖-控制器)】,然后點擊下一步
?打開配置新項目頁面,輸入【項目名稱】,然后點擊下一步
?在其他信息頁面,選擇框架【.NET 6.0(長期支持)】,身份驗證類型,選擇【個人賬戶】,然后點擊【創(chuàng)建】,如下所示:
?生成的項目將?ASP.NET Core Identity作為Razor類庫提供。 IdentityRazor 類庫公開具有?Identity
?區(qū)域的終結(jié)點。
2. 創(chuàng)建數(shù)據(jù)庫
在數(shù)據(jù)庫管理器中,創(chuàng)建空數(shù)據(jù)庫,如下所示:
3. 修改數(shù)據(jù)庫連接字符串
在創(chuàng)建好后的項目中,打開項目配置文件【appsettings.json】,修改默認(rèn)數(shù)據(jù)庫連字符串,如下所示:
?4. 數(shù)據(jù)庫更新遷移
通過VisualStudio打開程序包管理器控制臺
?,輸入以下命令【Update-Database】,進(jìn)行數(shù)據(jù)庫遷移,如下所示:
?待執(zhí)行數(shù)據(jù)遷移成功后,打開剛剛創(chuàng)建的數(shù)據(jù)庫,發(fā)現(xiàn)多出了幾個表,如下所示:
?如此,則表示遷移成功。
之所以能夠遷移成功,是因為模板在創(chuàng)建項目時,已經(jīng)為我們創(chuàng)建了初始化腳本,如下所示:
5. 配置Identity服務(wù)
根據(jù)官方文檔,注入Identity相關(guān)服務(wù),如下所示:
1 using DemoCoreIdentity.Data; 2 using Microsoft.AspNetCore.Identity; 3 using Microsoft.EntityFrameworkCore; 4 5 var builder = WebApplication.CreateBuilder(args); 6 7 // Add services to the container. 8 var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); 9 builder.Services.AddDbContext<ApplicationDbContext>(options => 10 options.UseSqlServer(connectionString)); 11 builder.Services.AddDatabaseDeveloperPageExceptionFilter(); 12 13 #region Identity 14 15 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) 16 .AddEntityFrameworkStores<ApplicationDbContext>(); 17 builder.Services.AddControllersWithViews(); 18 19 builder.Services.Configure<IdentityOptions>(options => 20 { 21 // Password settings. 22 options.Password.RequireDigit = true; 23 options.Password.RequireLowercase = true; 24 options.Password.RequireNonAlphanumeric = true; 25 options.Password.RequireUppercase = true; 26 options.Password.RequiredLength = 6; 27 options.Password.RequiredUniqueChars = 1; 28 29 // Lockout settings. 30 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); 31 options.Lockout.MaxFailedAccessAttempts = 5; 32 options.Lockout.AllowedForNewUsers = true; 33 34 // User settings. 35 options.User.AllowedUserNameCharacters = 36 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; 37 options.User.RequireUniqueEmail = false; 38 }); 39 40 builder.Services.ConfigureApplicationCookie(options => 41 { 42 // Cookie settings 43 options.Cookie.HttpOnly = true; 44 options.ExpireTimeSpan = TimeSpan.FromMinutes(5); 45 46 options.LoginPath = "/Identity/Account/Login"; 47 options.AccessDeniedPath = "/Identity/Account/AccessDenied"; 48 options.SlidingExpiration = true; 49 }); 50 51 #endregion 52 53 var app = builder.Build(); 54 55 // Configure the HTTP request pipeline. 56 if (app.Environment.IsDevelopment()) 57 { 58 app.UseMigrationsEndPoint(); 59 } 60 else 61 { 62 app.UseExceptionHandler("/Home/Error"); 63 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 64 app.UseHsts(); 65 } 66 67 app.UseHttpsRedirection(); 68 app.UseStaticFiles(); 69 70 app.UseRouting(); 71 72 app.UseAuthentication(); 73 app.UseAuthorization(); 74 75 app.MapControllerRoute( 76 name: "default", 77 pattern: "{controller=Home}/{action=Index}/{id?}"); 78 app.MapRazorPages(); 79 80 app.Run();
上述代碼用默認(rèn)選項值來配置 Identity。 可通過依賴關(guān)系注入向應(yīng)用提供服務(wù)。通過調(diào)用?UseAuthentication?啟用 Identity。?UseAuthentication
?向請求管道添加身份驗證中間件。
Identity測試
運(yùn)行程序,默認(rèn)打開Home/Index頁面
1. 注冊用戶
點擊注冊鏈接,打開注冊窗口,輸入用戶名,密碼,點擊注冊按鈕,如下所示:
?注意,如下注冊校驗不通過,會有錯誤信息提示,如下所示:
2. 登錄
注冊成功后,點擊登錄鏈接,即可打開登錄窗口,如下所示:
?登錄成功后,顯示如下所示
3. 登出
點擊Logout鏈接,可以登出,重新返回Home/Index首頁,并顯示未登錄狀態(tài)。如下所示:
身份驗證
通過模板創(chuàng)建的項目,默認(rèn)情況下,Home/Index是沒有身份驗證的,可以在HomeController增加Authorize特性,增加身份驗證,如下所示:
1 using DemoCoreIdentity.Models; 2 using Microsoft.AspNetCore.Authorization; 3 using Microsoft.AspNetCore.Mvc; 4 using System.Diagnostics; 5 6 namespace DemoCoreIdentity.Controllers 7 { 8 [Authorize] 9 public class HomeController : Controller 10 { 11 private readonly ILogger<HomeController> _logger; 12 13 public HomeController(ILogger<HomeController> logger) 14 { 15 _logger = logger; 16 } 17 18 public IActionResult Index() 19 { 20 return View(); 21 } 22 23 public IActionResult Privacy() 24 { 25 return View(); 26 } 27 28 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 29 public IActionResult Error() 30 { 31 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 32 } 33 } 34 }
注意,如果要對某一個action增加驗證,則可以將Authorize特性添加在action上,進(jìn)行更詳細(xì)的身份驗證。
添加成功后,再次運(yùn)行程序打開Home/Index時,則會自動跳轉(zhuǎn)到登錄頁面,如下所示:
文章來源:http://www.zghlxwxcb.cn/news/detail-487624.html
?以上就是ASP.NET Core MVC使用Identity進(jìn)行身份驗證的全部內(nèi)容。文章來源地址http://www.zghlxwxcb.cn/news/detail-487624.html
到了這里,關(guān)于ASP.NET Core MVC 從入門到精通之Identity入門的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!