asp.net core中如何使用cookie身份驗(yàn)證
背景
ASP.NET Core Identity 是一個(gè)完整的全功能身份驗(yàn)證提供程序,用于創(chuàng)建和維護(hù)登錄名。 但是, cookie 不能使用基于的身份驗(yàn)證提供程序 ASP.NET Core Identity 。
配置
在 Startup.ConfigureServices 方法中,創(chuàng)建具有 AddAuthentication 和 AddCookie 方法的身份驗(yàn)證中間件服務(wù):
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthentication();
AuthenticationScheme 傳遞到 AddAuthentication 設(shè)置應(yīng)用程序的默認(rèn)身份驗(yàn)證方案。如果有多個(gè) cookie 身份驗(yàn)證實(shí)例,并且你想要使用特定方案進(jìn)行授權(quán),AuthenticationScheme 會(huì)很有用。將 AuthenticationScheme 設(shè)置為CookieAuthenticationDefaults。AuthenticationScheme為方案提供值 "cookie"。可以提供任何用于區(qū)分方案的字符串值。
應(yīng)用的身份驗(yàn)證方案不同于應(yīng)用的 cookie 身份驗(yàn)證方案。如果未向 AddCookie提供 cookie 身份驗(yàn)證方案,則使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
默認(rèn)情況下,身份驗(yàn)證 cookie 的 IsEssential 屬性設(shè)置為 true。當(dāng)站點(diǎn)訪(fǎng)問(wèn)者未同意數(shù)據(jù)收集時(shí),允許使用身份驗(yàn)證 cookie。
登錄
若要?jiǎng)?chuàng)建保存用戶(hù)信息的 cookie,請(qǐng)構(gòu)造一個(gè) ClaimsPrincipal。將對(duì)用戶(hù)信息進(jìn)行序列化并將其存儲(chǔ)在 cookie 中。
使用任何所需的 Claim創(chuàng)建 ClaimsIdentity,并調(diào)用 SignInAsync 以登錄用戶(hù):
/// <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ù)驗(yàn)證失敗" });
}
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)用于加密。對(duì)于托管在多臺(tái)計(jì)算機(jī)上的應(yīng)用程序、跨應(yīng)用程序或使用 web 場(chǎng)進(jìn)行負(fù)載平衡,請(qǐng)將數(shù)據(jù)保護(hù)配置為使用相同的密鑰環(huán)和應(yīng)用程序標(biāo)識(shí)符。
注銷(xiāo)
若要注銷(xiāo)當(dāng)前用戶(hù)并刪除其 cookie,請(qǐng)調(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身份驗(yàn)證的文章就介紹到這了,更多相關(guān)asp.net core用cookie身份驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- ASP.NET?Core中Cookie驗(yàn)證身份用法詳解
- asp.core?同時(shí)兼容JWT身份驗(yàn)證和Cookies?身份驗(yàn)證兩種模式(示例詳解)
- .NET?Core支持Cookie和JWT混合認(rèn)證、授權(quán)的方法
- asp.net core3.1cookie和jwt混合認(rèn)證授權(quán)實(shí)現(xiàn)多種身份驗(yàn)證方案
- ASP.NET Core 使用Cookie驗(yàn)證身份的示例代碼
- 3分鐘快速學(xué)會(huì)在ASP.NET Core MVC中如何使用Cookie
- ASP.NET學(xué)習(xí)CORE中使用Cookie身份認(rèn)證方法
- 詳解在ASP.NET Core 中使用Cookie中間件
- 詳解ASP.NET與ASP.NET Core用戶(hù)驗(yàn)證Cookie并存解決方案
- ASP.NET?Core在WebApi項(xiàng)目中使用Cookie
相關(guān)文章
ASP.NET中MVC從后臺(tái)控制器傳遞數(shù)據(jù)到前臺(tái)視圖的方式
這篇文章主要介紹了ASP.NET中MVC從后臺(tái)控制器傳遞數(shù)據(jù)到前臺(tái)視圖的方式,以實(shí)例形式較為詳細(xì)的分析了asp.net中MVC數(shù)據(jù)傳遞的具體實(shí)現(xiàn)方法,需要的朋友可以參考下2014-12-12
ASP.NET?MVC實(shí)現(xiàn)區(qū)域路由
這篇文章介紹了ASP.NET?MVC實(shí)現(xiàn)區(qū)域路由的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
.Net中關(guān)于stirng轉(zhuǎn)System.Type的一種實(shí)現(xiàn)思路詳解
這篇文章主要給大家介紹了.Net中關(guān)于stirng轉(zhuǎn)System.Type的一種實(shí)現(xiàn)思路的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05
asp.net 不用GridView自帶刪除功能,刪除一行數(shù)據(jù)
數(shù)據(jù)表一定要有個(gè)ID的主鍵值,你的gridview要設(shè)定一下DataKeyNames="ID"這個(gè)屬性值,接下的事件就好多了,寫(xiě)個(gè)OnRowDeleting事件就可以了。2009-11-11
ASP.NET Core中Grpc通信的簡(jiǎn)單用法
這篇文章介紹了ASP.NET Core中Grpc通信的簡(jiǎn)單用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
解決AJAX.NET中的懸停panel在頁(yè)面加載時(shí)閃爍的問(wèn)題
AJAX.NET的兩個(gè)懸??丶?分別是HoverMenuExtender和ModalPopupExtender.他們可以打造很好的懸停效果...通常,我都是用panel來(lái)作為懸停內(nèi)容的容器..2009-06-06
C# FTP,GetResponse(),遠(yuǎn)程服務(wù)器返回錯(cuò)誤
C# FTP,GetResponse(),遠(yuǎn)程服務(wù)器返回錯(cuò)誤:(550) 文件不可用(例如,未找到文件,無(wú)法訪(fǎng)問(wèn)文件)2009-06-06
解析.netcore項(xiàng)目中IStartupFilter使用教程
netcore項(xiàng)目中有些服務(wù)是在通過(guò)中間件來(lái)通信的,比如orleans組件,今天通過(guò)實(shí)例代碼給大家介紹下netcore項(xiàng)目中IStartupFilter使用教程,感興趣的朋友一起看看吧2021-11-11

