asp.net core中如何使用cookie身份验证
背景
ASP.NETCoreIdentity是一个完整的全功能身份验证提供程序,用于创建和维护登录名。但是,cookie不能使用基于的身份验证提供程序ASP.NETCoreIdentity。
配置
在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] publicasyncTask Login(LoginModelmodel,stringreturnUrl=null) { if(!ModelState.IsValid) { returnJson(new{state="error",message="数据验证失败"}); } 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="登录成功。",returnUrl=RedirectToLocal(returnUrl)}); }
SignInAsync创建加密的cookie,并将其添加到当前响应中。如果未指定AuthenticationScheme,则使用默认方案。
ASP.NETCore的数据保护系统用于加密。对于托管在多台计算机上的应用程序、跨应用程序或使用web场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。
注销
若要注销当前用户并删除其cookie,请调用SignOutAsync:
////// /// ///[HttpPost] [ValidateAntiForgeryToken] publicasyncTask LogOff() { if(bool.Parse(Configuration.GetSection("IsIdentity").Value)) { returnSignOut("Cookies","oidc"); } else { if(User.Identity.IsAuthenticated) { stringuserdata=User.Claims.FirstOrDefault(o=>o.Type==ClaimTypes.UserData)?.Value; awaitUserApp.LogOffAsync(CurrentUser.FromJson(userdata)); } awaitHttpContext.SignOutAsync( CookieAuthenticationDefaults.AuthenticationScheme); returnRedirectToAction(actionName:nameof(Login),controllerName:"Account"); } }
参考资料
https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-5.0
到此这篇关于asp.netcore中如何使用cookie身份验证的文章就介绍到这了,更多相关asp.netcore用cookie身份验证内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!