asp.net core中如何使用cookie身份验证
背景
ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名。 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity 。
配置
在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthentication();
AuthenticationScheme 传递到 AddAuthentication 设置应用程序的默认身份验证方案。如果有多个 cookie 身份验证实例,并且你想要使用特定方案进行授权,AuthenticationScheme 会很有用。将 AuthenticationScheme 设置为CookieAuthenticationDefaults。AuthenticationScheme为方案提供值 "cookie"。可以提供任何用于区分方案的字符串值。
应用的身份验证方案不同于应用的 cookie 身份验证方案。如果未向 AddCookie提供 cookie 身份验证方案,则使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
默认情况下,身份验证 cookie 的 IsEssential 属性设置为 true。当站点访问者未同意数据收集时,允许使用身份验证 cookie。
登录
若要创建保存用户信息的 cookie,请构造一个 ClaimsPrincipal。将对用户信息进行序列化并将其存储在 cookie 中。
使用任何所需的 Claim创建 ClaimsIdentity,并调用 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 = "数据验证失败" });
}
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 创建加密的 cookie,并将其添加到当前响应中。如果未指定 AuthenticationScheme,则使用默认方案。
ASP.NET Core 的数据保护系统用于加密。对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。
注销
若要注销当前用户并删除其 cookie,请调用 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
到此这篇关于asp.net core中如何使用cookie身份验证的文章就介绍到这了,更多相关asp.net core用cookie身份验证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
- ASP.NET Core中Cookie验证身份用法详解
- asp.core 同时兼容JWT身份验证和Cookies 身份验证两种模式(示例详解)
- .NET Core支持Cookie和JWT混合认证、授权的方法
- asp.net core3.1cookie和jwt混合认证授权实现多种身份验证方案
- ASP.NET Core 使用Cookie验证身份的示例代码
- 3分钟快速学会在ASP.NET Core MVC中如何使用Cookie
- ASP.NET学习CORE中使用Cookie身份认证方法
- 详解在ASP.NET Core 中使用Cookie中间件
- 详解ASP.NET与ASP.NET Core用户验证Cookie并存解决方案
- ASP.NET Core在WebApi项目中使用Cookie
相关文章
.Net中关于stirng转System.Type的一种实现思路详解
这篇文章主要给大家介绍了.Net中关于stirng转System.Type的一种实现思路的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2018-05-05
asp.net 不用GridView自带删除功能,删除一行数据
数据表一定要有个ID的主键值,你的gridview要设定一下DataKeyNames="ID"这个属性值,接下的事件就好多了,写个OnRowDeleting事件就可以了。2009-11-11
解决AJAX.NET中的悬停panel在页面加载时闪烁的问题
AJAX.NET的两个悬停控件.分别是HoverMenuExtender和ModalPopupExtender.他们可以打造很好的悬停效果...通常,我都是用panel来作为悬停内容的容器..2009-06-06
C# FTP,GetResponse(),远程服务器返回错误
C# FTP,GetResponse(),远程服务器返回错误:(550) 文件不可用(例如,未找到文件,无法访问文件)2009-06-06
解析.netcore项目中IStartupFilter使用教程
netcore项目中有些服务是在通过中间件来通信的,比如orleans组件,今天通过实例代码给大家介绍下netcore项目中IStartupFilter使用教程,感兴趣的朋友一起看看吧2021-11-11


最新评论