配置
在 Startup.ConfigureServices 方法中,創建具有 AddAuthentication 和 AddCookie 方法的身份驗證中間件服務:
services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { // Cookie settings options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(20); options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; options.SlidingExpiration = true; });
AuthenticationScheme 傳遞到 AddAuthentication 設定應用程式的默認身份驗證方案, 如果有多個 cookie 身份驗證實體,并且你想要使用特定方案進行授權,AuthenticationScheme 會很有用, 將 AuthenticationScheme 設定為CookieAuthenticationDefaults, AuthenticationScheme為方案提供值 "cookie", 可以提供任何用于區分方案的字串值,
應用的身份驗證方案不同于應用的 cookie 身份驗證方案, 如果未向 AddCookie提供 cookie 身份驗證方案,則使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie"),
默認情況下,身份驗證 cookie 的 IsEssential 屬性設定為 true, 當站點訪問者未同意資料收集時,允許使用身份驗證 cookie,
在 Startup.Configure中,呼叫 UseAuthentication 和 UseAuthorization 設定 HttpContext.User 屬性,并為請求運行授權中間件, 呼叫 UseEndpoints之前呼叫 UseAuthentication 和 UseAuthorization 方法:
app.UseCookiePolicy();
app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints =>{ endpoints.MapControllers(); endpoints.MapRazorPages();});
登錄
若要創建保存用戶資訊的 cookie,請構造一個 ClaimsPrincipal, 將對用戶資訊進行序列化并將其存盤在 cookie 中,
使用任何所需的 Claim創建 ClaimsIdentity,并呼叫 SignInAsync 以登錄用戶:
var claims = new List<Claim>{new Claim(ClaimTypes.Name, user.Email),new Claim("FullName", user.FullName),new Claim(ClaimTypes.Role, "Administrator"),};var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);var authProperties = new AuthenticationProperties{//AllowRefresh = <bool>,// Refreshing the authentication session should be allowed.//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),// The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie.//IsPersistent = true,// Whether the authentication session is persisted across // multiple requests. When used with cookies, controls// whether the cookie's lifetime is absolute (matching the// lifetime of the authentication ticket) or session-based.//IssuedUtc = <DateTimeOffset>,// The time at which the authentication ticket was issued.//RedirectUri = <string>// The full path or absolute URI to be used as an http // redirect response value.};await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
SignInAsync 創建加密的 cookie,并將其添加到當前回應中, 如果未指定 AuthenticationScheme,則使用默認方案,
ASP.NET Core 的資料保護系統用于加密, 對于托管在多臺計算機上的應用程式、跨應用程式或使用 web 場進行負載平衡,請將資料保護配置為使用相同的密鑰環和應用程式識別符號,
注銷
若要注銷當前用戶并洗掉其 cookie,請呼叫 SignOutAsync:
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
如果 CookieAuthenticationDefaults.AuthenticationScheme (或 "Cookie")不用作方案(例如 "ContosoCookie"),請提供配置身份驗證提供程式時所使用的方案, 否則,將使用默認方案,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4457.html
標籤:ASP.NET
