在 http:// ASP.NET Core 中使用Cookie中間件
ASP.NET Core 提供了Cookie中間件來(lái)序列化用戶主題到一個(gè)加密的Cookie中并且在后來(lái)的請(qǐng)求中校驗(yàn)這個(gè)Cookie,再現(xiàn)用戶并且分配到HttpContext對(duì)象的User屬性中。如果你想提供自己的登錄方式和用戶數(shù)據(jù)你可以使用Cookie中間件來(lái)實(shí)現(xiàn)獨(dú)立的功能。
添加和配置
第一步是增加Cookie中間件到你的應(yīng)用中。首先使用nuget增加Microsoft.AspNetCore.Authentication.Cookies 程序包。然后添加下面的幾行代碼到Startup.cs文件的Configure方法中,且要在app.UseMvc()之前。
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", LoginPath = new PathString("/Account/Unauthorized/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
上面的代碼片段配置了一下幾個(gè)選項(xiàng);
其他選項(xiàng)包括設(shè)置中間件所創(chuàng)建的聲明的發(fā)行者,中間件存儲(chǔ)的cookie名稱,Cookie的域和cookie上的各種安全屬性。默認(rèn)情況下Cookie中間件將使用適當(dāng)?shù)陌踩x項(xiàng),設(shè)置HTTPONLY避免cookie在客戶端被JavaScript操作。當(dāng)請(qǐng)求方式為HTTPS時(shí)限制Cookie的HTTPS操作。
創(chuàng)建Cookie
創(chuàng)建Cookie保存自己的信息,必須要初始化一個(gè)ClaimsPrincipal(類型)來(lái)序列化和保存你想保存的用戶信息到Cookie中。每一次的方法調(diào)用都會(huì)在你的Controller(控制器)中有一個(gè)合適的ClaimsPrincipal對(duì)象。
上面的代碼將會(huì)創(chuàng)建一個(gè)加密的Cookie并且增加到當(dāng)前的請(qǐng)求響應(yīng)中。AuthenticationScheme明確規(guī)定在配置期間
退出
退出當(dāng)前用戶的登錄,刪除登錄的cookie信息,可以在控制器中調(diào)用下面的方法。
響應(yīng)后端的變化
警告
一旦cookie創(chuàng)建就會(huì)成為身份單一認(rèn)證的來(lái)源,即使在后臺(tái)系統(tǒng)已經(jīng)不可用,中間件也是不知道的,并且始終保持登錄直到cookie失效。
Cookie認(rèn)證中間件在他的選項(xiàng)類中提供了一系列的事件,其中 ValidateAsync() 事件可以用來(lái)中斷和重寫cookie認(rèn)證的驗(yàn)證方法。
考慮到后臺(tái)用戶的數(shù)據(jù)庫(kù)中可能會(huì)有‘最后的修改時(shí)間'這一列,為了在數(shù)據(jù)庫(kù)修改之后你可以廢止當(dāng)前的Cookie,第一當(dāng)創(chuàng)建這個(gè)Cookie時(shí)添加一個(gè)最后修改的聲明并包含當(dāng)前的值,當(dāng)數(shù)據(jù)庫(kù)中的數(shù)據(jù)改變時(shí),這個(gè)值也同時(shí)更新。
實(shí)現(xiàn)一個(gè)ValidateAsync()的事件重寫你必須寫一個(gè)具有如下簽名的方法。
Task ValidateAsync(CookieValidatePrincipalContext context);
http:// ASP.NET Core 認(rèn)證在SecurityStampValidator中實(shí)現(xiàn)了這個(gè)驗(yàn)證。下面是一個(gè)類似的例子:
public static class LastChangedValidator { public static async Task ValidateAsync(CookieValidatePrincipalContext context) { // Pull database from registered DI services. var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>(); var userPrincipal = context.Principal; // Look for the last changed claim. string lastChanged; lastChanged = (from c in userPrincipal.Claims where c.Type == "LastUpdated" select c.Value).FirstOrDefault(); if (string.IsNullOrEmpty(lastChanged) || !userRepository.ValidateLastChanged(userPrincipal, lastChanged)) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); } } }
這些要在Cookie中間件配置時(shí)進(jìn)行注冊(cè)
app.UseCookieAuthentication(options => { options.Events = new CookieAuthenticationEvents { // Set other options OnValidatePrincipal = LastChangedValidator.ValidateAsync }; });
如果你想非破壞性的更新用戶主體,例如,name更新了,要想以不影響安全的方式你可以調(diào)用 context.ReplacePrincipal() 并且設(shè)置 context.ShouldRenew 為 true 。
控制Cookie選項(xiàng)
CookieAuthenticationOptions配備了各種各樣的配置選項(xiàng)是你能夠很好的調(diào)節(jié)創(chuàng)建的Cookie。
持續(xù)性Cookie和絕對(duì)過(guò)期時(shí)間
您可能希望通過(guò)瀏覽器會(huì)話使cookie過(guò)期。也許你也想通過(guò)絕對(duì)過(guò)期時(shí)間和認(rèn)證來(lái)結(jié)束cookie,那么你可以在登錄認(rèn)證和創(chuàng)建Cookie時(shí)使用HttpContext.Authentication.SignInAsync方法中的AuthenticationProperties參數(shù)類實(shí)現(xiàn)。AuthenticationProperties類在Microsoft.AspNetCore.Http.Authentication命名空間中。
例如
await HttpContext.Authentication.SignInAsync( "MyCookieMiddlewareInstance", principal, new AuthenticationProperties { IsPersistent = true });
這個(gè)代碼片段將會(huì)實(shí)現(xiàn)創(chuàng)建一個(gè)認(rèn)證和相應(yīng)的Cookie來(lái)實(shí)現(xiàn)即時(shí)瀏覽器關(guān)閉Cookie也能繼續(xù)保留。任何在cookie屬性中的過(guò)期時(shí)間的設(shè)置都將會(huì)保存下來(lái)。如果瀏覽器關(guān)閉時(shí)Cookie也過(guò)期了那么在重新啟動(dòng)瀏覽器是Cookie將會(huì)別清理。
await HttpContext.Authentication.SignInAsync( "MyCookieMiddlewareInstance", principal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20) });
這段代碼將創(chuàng)建一個(gè)身份認(rèn)證和相應(yīng)的cookie且將持續(xù)20分鐘。 任何在Cookie options中配置的動(dòng)態(tài)選項(xiàng)都會(huì)被忽略。 ExpiresUtc 和 IsPersistent 這兩個(gè)屬性是相互獨(dú)立的。
其實(shí)上面bb了那么多,都沒(méi)用! 不如來(lái)個(gè)demo
// 1. 在Startup.cs的Configure方法中加上app.UseCookieAuthentication(new CookieAuthenticationOptions{ AuthenticationScheme = "UserAuth", // Cookie 驗(yàn)證方案名稱,在寫cookie時(shí)會(huì)用到。 AutomaticAuthenticate = true, // 是否自動(dòng)啟用驗(yàn)證,如果不啟用,則即便客服端傳輸了Cookie信息,服務(wù)端也不會(huì)主動(dòng)解析。除了明確配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 屬性的地方,才會(huì)解析,此功能一般用在需要在同一應(yīng)用中啟用多種驗(yàn)證方案的時(shí)候。比如分Area. LoginPath = "/User/Index" // 登錄頁(yè)});// 2. 新建UserController// 3. 創(chuàng)建一個(gè)測(cè)試登錄的方法(這里為了方便測(cè)是我用的是get方法,方便傳參請(qǐng)求)public IActionResult Login(int userId, string userName){ WriteUser(userId, userName); return Content("Write");}private async void WriteUser(int userId, string userName){ var identity = new ClaimsIdentity("Forms"); // 指定身份認(rèn)證類型 identity.AddClaim(new Claim(ClaimTypes.Sid, userId.ToString())); // 用戶Id identity.AddClaim(new Claim(ClaimTypes.Name, userName)); // 用戶名稱 var principal = new ClaimsPrincipal(identity); await HttpContext.Authentication.SignInAsync("UserAuth", principal, new AuthenticationProperties { IsPersistent = true , ExpiresUtc = DateTime.UtcNow.AddMinutes(20) }); //過(guò)期時(shí)間20分鐘}// 4. 創(chuàng)建一個(gè)退出登錄的方法public async Task<ActionResult> Logout(){ await HttpContext.Authentication.SignOutAsync("UserAuth"); // Startup.cs中配置的驗(yàn)證方案名 return RedirectToAction("User", "Index");}// 5. 創(chuàng)建一個(gè)獲取cookie用戶信息的方法方便調(diào)用private int GetUserId(){ //var userName = User.Identity.Name; //獲取登錄時(shí)存儲(chǔ)的用戶名稱 var userId = User.FindFirst(ClaimTypes.Sid).Value; // 獲取登錄時(shí)存儲(chǔ)的Id if (string.IsNullOrEmpty(userId)) { return 0; } else { return int.Parse(userId); }}// 或者寫一個(gè)測(cè)試Actionpublic JsonResult CheckLogin(){ var userName = User.Identity.Name; //獲取登錄時(shí)存儲(chǔ)的用戶名稱 var userId = User.FindFirst(ClaimTypes.Sid).Value; // 獲取登錄時(shí)存儲(chǔ)的Id return Json({UserId:userId,UserName:userName});}// 6. 以上是加密的方式如果直接寫好像也是可以的HttpContext.Response.Cookies.Append("Key", "Value");
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選