asp.net core中-国外idc-如何使用cookie身份验证

这篇文章首要介绍了asp.net core中-国外idc如何运用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 以登录用户:

///
///
///
///
///
///
[HttpPost]
[AllowAttribute]
[ValidateAntiForgeryToken]
public async TaskLogin(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
{
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:

///
///
///
///
[HttpPost]
[ValidateAntiForgeryToken]
public async TaskLogOff()
{
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

共有 0 条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注