当前位置: 首页 > 科技观察

Asp.netcore使用cookie认证

时间:2023-03-19 12:42:57 科技观察

本文转载自微信公众号《UP技控》,作者conan5566。转载本文请联系UP技控公众号。conan5566背景ASP.NETCoreIdentity是一个功能齐全的身份验证提供程序,用于创建和维护登录。但是,cookie不能使用基于ASP.NETCoreIdentity的身份验证提供程序。Configure在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]publicasyncTaskLogin(LoginModelmodel,stringreturnUrl=null){if(!ModelState.IsValid){returnJson(new{state="error",message="dataverificationfailed"});}stringip=GetRemoteIpAddress();varr=awaitUserApp.SaasLoginAsync(model.Account,model.Password,ip);if(!string.IsNullOrEmpty(r.Error)){returnJson(new{state="error",message=r.Error});}varclaims=newList{newClaim(ClaimTypes.UserData,getCurrentUser(r.User,ip).ToString()),};varclaimsIdentity=newClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);varauthProperties=newAuthenticationProperties{ExpiresUtc=DateTimeOffset.Now.AddMinutes(120)};awaitHttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,newClaimsPrincipal(claimsIdentity),authProperties);returnJson(new{state="success",message="loginsuccessful",returnUrl=RedirectToLocal(returnUrl)});}SignInAsync创建一个加密的cookie并将其添加到当前的响应。如果未指定AuthenticationScheme,则使用默认方案。ASP.NETCore的数据保护系统用于加密。对于托管在多台机器上、跨应用程序负载平衡或使用网络场的应用程序,将数据保护配置为使用相同的密钥环和应用程序标识符。注销要注销当前用户并删除他们的cookie,请调用SignOutAsync:////////////[HttpPost][ValidateAntiForgeryToken]publicasyncTaskLogOff(){if(bool.Parse(Configuration.GetSection("IsIdentity").Value)){returnSignOut("Cookies","oidc");}else{if(User.Identity.IsAuthenticated){stringuserdata=用户。Claims.FirstOrDefault(o=>o.Type==ClaimTypes.UserData)?.Value;awaitUserApp.LogOffAsync(CurrentUser.FromJson(userdata));}awaitHttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);returnRedirectToAction(actionName:nameof(登录),controllerName:"Account");}}参考https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-5.0