Asp.net core中使用cookie身份验证

安全 应用安全
ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名。 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity 。

[[381956]]

本文转载自微信公众号「UP技术控」,作者conan5566。转载本文请联系UP技术控公众号。conan5566  

背景

ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名。 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity 。

配置

在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务:

  1. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); 
  1. 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 以登录用户:

  1. /// <summary> 
  2.         /// 
  3.         /// </summary> 
  4.         /// <param name="model"></param> 
  5.         /// <param name="returnUrl"></param> 
  6.         /// <returns></returns
  7.         [HttpPost] 
  8.         [AllowAttribute] 
  9.         [ValidateAntiForgeryToken] 
  10.         public async Task<IActionResult> Login(LoginModel model, string returnUrl = null
  11.         { 
  12.             if (!ModelState.IsValid) 
  13.             { 
  14.                 return Json(new { state = "error", message = "数据验证失败" }); 
  15.             } 
  16.             string ip = GetRemoteIpAddress(); 
  17.             var r = await UserApp.SaasLoginAsync(model.Account, model.Password, ip); 
  18.             if (!string.IsNullOrEmpty(r.Error)) 
  19.             { 
  20.                 return Json(new { state = "error", message = r.Error }); 
  21.             } 
  22.             var claims = new List<Claim> 
  23.                                         { 
  24.                                             new Claim(ClaimTypes.UserData, getCurrentUser(r.User, ip).ToString()), 
  25.                                         }; 
  26.             var claimsIdentity = new ClaimsIdentity( 
  27.                 claims, CookieAuthenticationDefaults.AuthenticationScheme); 
  28.             var authProperties = new AuthenticationProperties 
  29.             { 
  30.                 ExpiresUtc = DateTimeOffset.Now.AddMinutes(120) 
  31.             }; 
  32.             await HttpContext.SignInAsync( 
  33.                 CookieAuthenticationDefaults.AuthenticationScheme, 
  34.                 new ClaimsPrincipal(claimsIdentity), 
  35.                 authProperties); 
  36.             return Json(new { state = "success", message = "登录成功。", returnUrl = RedirectToLocal(returnUrl) }); 
  37.         } 

SignInAsync 创建加密的 cookie,并将其添加到当前响应中。如果未指定 AuthenticationScheme,则使用默认方案。

ASP.NET Core 的数据保护系统用于加密。对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。

注销

若要注销当前用户并删除其 cookie,请调用 SignOutAsync:

  1. /// <summary> 
  2.         /// 
  3.         /// </summary> 
  4.         /// <returns></returns
  5.         [HttpPost] 
  6.         [ValidateAntiForgeryToken] 
  7.         public async Task<IActionResult> LogOff() 
  8.         { 
  9.             if (bool.Parse(Configuration.GetSection("IsIdentity").Value)) 
  10.             { 
  11.                 return SignOut("Cookies""oidc"); 
  12.             } 
  13.             else 
  14.             { 
  15.                 if (User.Identity.IsAuthenticated) 
  16.                 { 
  17.                     string userdata = User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.UserData)?.Value; 
  18.                     await UserApp.LogOffAsync(CurrentUser.FromJson(userdata)); 
  19.                 } 
  20.                 await HttpContext.SignOutAsync( 
  21.                  CookieAuthenticationDefaults.AuthenticationScheme); 
  22.                 return RedirectToAction(actionName: nameof(Login), controllerName: "Account"); 
  23.             } 
  24.         } 

参考资料

https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-5.0

 

责任编辑:武晓燕 来源: UP技术控
相关推荐

2009-07-29 12:55:44

ASP.NET身份验证

2011-05-23 10:37:03

2009-07-29 16:47:40

ASP.NET表单身份

2012-06-04 09:36:50

2021-02-02 16:19:08

Serilog日志框架

2021-02-06 21:40:13

SignalR通讯TypeScript

2021-03-17 09:45:31

LazyCacheWindows

2021-01-31 22:56:50

FromServiceASP

2021-03-10 09:40:43

LamarASP容器

2021-01-07 07:39:07

工具接口 Swagger

2021-02-03 13:35:25

ASPweb程序

2021-01-28 22:39:35

LoggerMessa开源框架

2021-02-28 20:56:37

NCache缓存框架

2021-03-03 22:37:16

MediatR中介者模式

2021-02-07 17:29:04

监视文件接口

2014-12-11 10:05:13

ASP.NET

2021-06-22 16:59:56

微软.NETC# 软件开发

2021-01-26 14:57:00

中间件应用模块化

2021-01-04 05:44:54

框架日志

2021-04-12 07:03:10

轻量级模块化框架
点赞
收藏

51CTO技术栈公众号