asp.net core中如何使用cookie身份驗證
背景
ASP.NET Core Identity 是一個完整的全功能身份驗證提供程序,用于創(chuàng)建和維護(hù)登錄名。 但是, cookie 不能使用基于的身份驗證提供程序 ASP.NET Core Identity 。
配置
在 Startup.ConfigureServices 方法中,創(chuàng)建具有 AddAuthentication 和 AddCookie 方法的身份驗證中間件服務(wù):
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthentication();
AuthenticationScheme 傳遞到 AddAuthentication 設(shè)置應(yīng)用程序的默認(rèn)身份驗證方案。如果有多個 cookie 身份驗證實例,并且你想要使用特定方案進(jìn)行授權(quán),AuthenticationScheme 會很有用。將 AuthenticationScheme 設(shè)置為CookieAuthenticationDefaults。AuthenticationScheme為方案提供值 "cookie"??梢蕴峁┤魏斡糜趨^(qū)分方案的字符串值。
應(yīng)用的身份驗證方案不同于應(yīng)用的 cookie 身份驗證方案。如果未向 AddCookie提供 cookie 身份驗證方案,則使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
默認(rèn)情況下,身份驗證 cookie 的 IsEssential 屬性設(shè)置為 true。當(dāng)站點訪問者未同意數(shù)據(jù)收集時,允許使用身份驗證 cookie。
登錄
若要創(chuàng)建保存用戶信息的 cookie,請構(gòu)造一個 ClaimsPrincipal。將對用戶信息進(jìn)行序列化并將其存儲在 cookie 中。
使用任何所需的 Claim創(chuàng)建 ClaimsIdentity,并調(diào)用 SignInAsync 以登錄用戶:
/// <summary>
///
/// </summary>
/// <param name="model"></param>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpPost]
[AllowAttribute]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return Json(new { state = "error", message = "數(shù)據(jù)驗證失敗" });
}
string ip = GetRemoteIpAddress();
var r = await UserApp.SaasLoginAsync(model.Account, model.Password, ip);
if (!string.IsNullOrEmpty(r.Error))
{
return Json(new { state = "error", message = r.Error });
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.UserData, getCurrentUser(r.User, ip).ToString()),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
ExpiresUtc = DateTimeOffset.Now.AddMinutes(120)
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Json(new { state = "success", message = "登錄成功。", returnUrl = RedirectToLocal(returnUrl) });
}
SignInAsync 創(chuàng)建加密的 cookie,并將其添加到當(dāng)前響應(yīng)中。如果未指定 AuthenticationScheme,則使用默認(rèn)方案。
ASP.NET Core 的數(shù)據(jù)保護(hù)系統(tǒng)用于加密。對于托管在多臺計算機上的應(yīng)用程序、跨應(yīng)用程序或使用 web 場進(jìn)行負(fù)載平衡,請將數(shù)據(jù)保護(hù)配置為使用相同的密鑰環(huán)和應(yīng)用程序標(biāo)識符。
注銷
若要注銷當(dāng)前用戶并刪除其 cookie,請調(diào)用 SignOutAsync:
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
if (bool.Parse(Configuration.GetSection("IsIdentity").Value))
{
return SignOut("Cookies", "oidc");
}
else
{
if (User.Identity.IsAuthenticated)
{
string userdata = User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.UserData)?.Value;
await UserApp.LogOffAsync(CurrentUser.FromJson(userdata));
}
await HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction(actionName: nameof(Login), controllerName: "Account");
}
}
參考資料
https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-5.0
到此這篇關(guān)于asp.net core中如何使用cookie身份驗證的文章就介紹到這了,更多相關(guān)asp.net core用cookie身份驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- ASP.NET?Core中Cookie驗證身份用法詳解
- asp.core?同時兼容JWT身份驗證和Cookies?身份驗證兩種模式(示例詳解)
- .NET?Core支持Cookie和JWT混合認(rèn)證、授權(quán)的方法
- asp.net core3.1cookie和jwt混合認(rèn)證授權(quán)實現(xiàn)多種身份驗證方案
- ASP.NET Core 使用Cookie驗證身份的示例代碼
- 3分鐘快速學(xué)會在ASP.NET Core MVC中如何使用Cookie
- ASP.NET學(xué)習(xí)CORE中使用Cookie身份認(rèn)證方法
- 詳解在ASP.NET Core 中使用Cookie中間件
- 詳解ASP.NET與ASP.NET Core用戶驗證Cookie并存解決方案
- ASP.NET?Core在WebApi項目中使用Cookie
相關(guān)文章
深入解析.NET 許可證編譯器 (Lc.exe) 的原理與源代碼剖析
許可證編譯器 (Lc.exe) 的作用是讀取包含授權(quán)信息的文本文件,并產(chǎn)生一個可作為資源嵌入到公用語言運行庫可執(zhí)行文件中的 .licenses 文件2013-07-07
關(guān)于利用RabbitMQ實現(xiàn)延遲任務(wù)的方法詳解
最近在使用RabbitMQ來實現(xiàn)延遲任務(wù)的時候發(fā)現(xiàn),這其中的知識點還是挺多的,所以下面這篇文章主要給大家介紹了關(guān)于利用RabbitMQ實現(xiàn)延遲任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-12-12
asp.net下模態(tài)對話框關(guān)閉之后繼續(xù)執(zhí)行服務(wù)器端代碼的問題
asp.net下模態(tài)對話框關(guān)閉之后繼續(xù)執(zhí)行服務(wù)器端代碼的問題...2007-04-04
asp.net使用for循環(huán)實現(xiàn)Datalist的分列顯示功能
工程業(yè)績--用for循環(huán)代替了DataList多列顯示,得到2行四列的表格,需要內(nèi)存表的8行數(shù)據(jù)2009-12-12
關(guān)于DDD:管理"工作單元實例"的兩種模式的使用方法
本篇文章介紹了,關(guān)于DDD:管理"工作單元實例"的兩種模式的使用方法。需要的朋友參考下2013-04-04
ASP.NET項目開發(fā)中日期控件DatePicker如何使用
這篇文章主要為大家詳細(xì)介紹了ASP.NET項目開發(fā)中日期控件DatePicker的使用方法,感興趣的小伙伴們可以參考一下2016-04-04
Asp.Net實現(xiàn)FORM認(rèn)證的一些使用技巧(必看篇)
下面小編就為大家?guī)硪黄狝sp.Net實現(xiàn)FORM認(rèn)證的一些使用技巧(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08

