经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
Asp .Net Core 系列:详解鉴权(身份验证)以及实现 Cookie、JWT、自定义三种鉴权 (含源码解析)
来源:cnblogs  作者:Code技术分享  时间:2024/6/11 9:59:51  对本文有异议

什么是鉴权(身份验证)?

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

  1. 定义
    • 鉴权,又称身份验证,是确定用户身份的过程。它验证用户提供的凭据(如用户名和密码)是否有效,并据此确认用户是否具备访问系统的权利。
  2. 过程
    • 用户向系统提供凭据(如用户名和密码)。
    • 系统使用已注册的身份验证服务(如IAuthenticationService)和身份验证处理程序来验证这些凭据的有效性。
    • 如果凭据有效,系统将识别并确认用户的身份,然后用户可以访问系统。
  3. 方式
    • 传统的鉴权方式通常依赖于密码验证,但这种方式存在安全风险,如密码泄露或被盗用。
    • 为了提高安全性,现代系统常采用更加复杂的鉴权方式,如基于数字签名的认证授权(如JWT认证),这种方式通过验证数字签名的正确性来确定用户的身份。
  4. 与授权的关系
    • 鉴权与授权是两个不同的概念,但密切相关。鉴权是验证用户身份的过程,而授权是确定用户是否有权访问系统资源的过程。
    • 鉴权是授权的前提,只有经过鉴权确认用户身份后,才能进行授权操作。
  5. .NET Core中的实现
    • 在.NET Core中,身份验证服务由IAuthenticationService负责,并通过身份验证中间件使用。
    • 身份验证服务使用已注册的身份验证处理程序来完成与身份验证相关的操作。
    • 开发者可以通过配置和扩展身份验证服务来支持不同的鉴权方式,以满足不同应用场景的需求。

注入容器,将CookieAuthenticationHandler作为处理逻辑

CookieAuthenticationOptions 类中一些常用属性的说明:

  1. AuthenticationScheme:获取或设置用于此身份验证选项的身份验证方案的名称。这通常是唯一的标识符,用于在应用程序中区分不同的身份验证方案。
  2. CookieName:获取或设置用于存储身份验证信息的Cookie的名称。默认值是 ".AspNetCore.Cookies"。
  3. CookieDomain:获取或设置Cookie的域名。如果未设置,则默认为空字符串,这表示Cookie将仅与创建它的域名一起发送。
  4. CookiePath:获取或设置Cookie的路径。这定义了哪些路径的请求将发送Cookie。如果未设置,则默认为应用程序的根路径。
  5. CookieHttpOnly:获取或设置一个值,该值指示浏览器是否仅通过HTTP访问Cookie(即,不允许通过客户端脚本访问)。默认值为 true,这是一个安全特性,用于防止跨站脚本攻击(XSS)。
  6. CookieSecure:获取或设置Cookie的安全级别。可以是 CookieSecurePolicy.NoneCookieSecurePolicy.AlwaysCookieSecurePolicy.SameAsRequest。这决定了Cookie是否应通过HTTPS传输。
  7. CookieSameSite:获取或设置SameSite属性的值,该属性有助于防止跨站请求伪造(CSRF)攻击。可以是 SameSiteMode.NoneSameSiteMode.LaxSameSiteMode.Strict
  8. AccessDeniedPath:获取或设置当用户尝试访问他们未经授权的资源时应重定向到的路径。
  9. LoginPath:获取或设置当用户需要登录时应重定向到的路径。
  10. LogoutPath:获取或设置当用户注销时应重定向到的路径。
  11. SlidingExpiration:获取或设置一个值,该值指示是否应在每次请求时重置身份验证Cookie的过期时间。如果设置为 true,则每次用户请求页面时,Cookie的过期时间都会重置为其原始过期时间。这有助于在用户活跃时保持会话的活跃状态。
  12. ExpireTimeSpan:获取或设置身份验证Cookie在客户端上的过期时间。如果未设置,则Cookie将不会过期(但请注意,服务器可能会因其他原因使会话无效)。
  13. Events:获取或设置 CookieAuthenticationEvents 的实例,该实例包含可以在身份验证过程中调用的委托,以自定义行为(如重定向、登录后操作等)。

CookieAuthenticationEvents 类包含多个事件,这些事件在 Cookie 身份验证的不同阶段被触发:

  • OnRedirectToLogin: 当用户尝试访问需要身份验证的资源,但尚未登录时触发。
  • OnRedirectToAccessDenied: 当用户已登录,但尝试访问他们没有权限的资源时触发。
  • OnRedirectToLogout: 当用户登出时触发。
  • OnSigningIn: 在用户登录之前触发,但身份验证票据(ticket)已经被创建。
  • OnSignedIn: 在用户成功登录后触发。
  • OnSigningOut: 在用户登出之前触发,但身份验证票据尚未被移除。
  • OnSignedOut: 在用户成功登出后触发。
  • OnValidatePrincipal: 在每次请求时触发,用于验证身份验证票据的有效性。
  1. builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  2. .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
  3. {
  4. // 配置Cookie参数
  5. options.Cookie.Name = ".AspNetCore.Cookies"; // Cookie名称
  6. options.Cookie.HttpOnly = true; // 限制Cookie只能通过HTTP访问,不能通过客户端脚本访问
  7. options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 仅在HTTPS下传输Cookie
  8. options.Cookie.SameSite = SameSiteMode.Lax; // 设置SameSite属性
  9. options.LoginPath = "/Account/Login"; // 登录页面路径
  10. options.AccessDeniedPath = "/Account/AccessDenied"; // 访问被拒绝时重定向到的路径
  11. options.SlidingExpiration = true; // 是否在每次请求时滑动Cookie的过期时间
  12. options.ExpireTimeSpan = TimeSpan.FromHours(1); // Cookie过期时间
  13. // 如果需要,你还可以配置其他事件,如登录成功、登出成功等
  14. //options.Events = new CookieAuthenticationEvents()
  15. //{
  16. // OnRedirectToAccessDenied = context =>
  17. // {
  18. // return context.Response.WriteAsJsonAsync(new
  19. // {
  20. // Result = false,
  21. // Message = "访问失败,请先登录"
  22. // });
  23. // },
  24. // OnValidatePrincipal = context =>
  25. // {
  26. // return context.Response.WriteAsJsonAsync(new
  27. // {
  28. // Result = false,
  29. // Message = "访问失败,请先登录"
  30. // });
  31. // },
  32. // OnRedirectToLogin = context =>
  33. // {
  34. // return context.Response.WriteAsJsonAsync(new
  35. // {
  36. // Result = false,
  37. // Message = "访问失败,请先登录"
  38. // });
  39. // },
  40. //};
  41. });

使用中间件加入管道,用于找到鉴权HttpContext.AuthenticateAsync()

  1. //鉴权 (核心源码就是AuthenticationMiddleware中间件)
  2. app.UseAuthentication();
  3. //授权 使用Authorize必须配置app.UseAuthorization();
  4. app.UseAuthorization();

在登录时写入凭证

ClaimsPrincipal:代表当前经过身份验证的用户的主体,验证后附加到HTTP请求的上下文中,通常可以通过 HttpContext.User 属性来访问

ClaimsIdentity:表示一个特定的身份,并存储与该用户相关的所有声明

Claim:用于描述用户的某个属性或权限,例如用户名、电子邮件地址、角色等

  1. /// <summary>
  2. /// http://localhost:5555/Auth/Login?name=admin&password=123456
  3. /// </summary>
  4. /// <param name="name"></param>
  5. /// <param name="password"></param>
  6. /// <returns></returns>
  7. public async Task<IActionResult> Login(string name, string password)
  8. {
  9. if ("admin".Equals(name, StringComparison.CurrentCultureIgnoreCase)
  10. && password.Equals("123456"))//等同于去数据库校验
  11. {
  12. var claimIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
  13. claimIdentity.AddClaim(new Claim(ClaimTypes.Name, name));
  14. claimIdentity.AddClaim(new Claim(ClaimTypes.Email, "2545233857@qq.com"));
  15. claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
  16. claimIdentity.AddClaim(new Claim(ClaimTypes.Country, "Chinese"));
  17. claimIdentity.AddClaim(new Claim(ClaimTypes.DateOfBirth, "1998"));
  18. await base.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity), new AuthenticationProperties
  19. {
  20. ExpiresUtc = DateTime.UtcNow.AddSeconds(30),
  21. });
  22. return new JsonResult(new
  23. {
  24. Result = true,
  25. Message = "登录成功"
  26. });
  27. }
  28. else
  29. {
  30. await Task.CompletedTask;
  31. return new JsonResult(new
  32. {
  33. Result = false,
  34. Message = "登录失败"
  35. });
  36. }
  37. }

在其他控制器上标记[Authorize]特性,在访问接口框架会自动进行鉴权并将身份信息写入上下文

  • [AllowAnonymous]:匿名可访问
  • [Authorize]:必须登录才可访问
  1. // <summary>
  2. /// 不需要权限就能访问---
  3. /// http://localhost:5555/Auth/Index
  4. /// 但是项目里面总有些数据是要登陆后才能看到的
  5. /// </summary>
  6. /// <returns></returns>
  7. [AllowAnonymous]
  8. public IActionResult Index()
  9. {
  10. return View();
  11. }
  12. /// <summary>
  13. /// 要求登陆后才能看到,没登陆是不能看的
  14. /// http://localhost:5555/Auth/Info
  15. /// </summary>
  16. /// <returns></returns>
  17. [Authorize]//表明该Action需要鉴权通过---得有鉴权动作
  18. public IActionResult Info()
  19. {
  20. return View();
  21. }

image

在登出时清理凭证

  1. /// <summary>
  2. /// 退出登陆
  3. /// http://localhost:5555/Auth/Logout
  4. /// </summary>
  5. /// <returns></returns>
  6. public async Task<IActionResult> Logout()
  7. {
  8. await base.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
  9. return new JsonResult(new
  10. {
  11. Result = true,
  12. Message = "退出成功"
  13. });
  14. }

源码

https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs

  1. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  2. {
  3. //确保Cookie票据(验证Cookie)
  4. var result = await EnsureCookieTicket();
  5. if (!result.Succeeded)
  6. {
  7. return result;
  8. }
  9. // We check this before the ValidatePrincipal event because we want to make sure we capture a clean clone
  10. // without picking up any per-request modifications to the principal.
  11. await CheckForRefreshAsync(result.Ticket);
  12. Debug.Assert(result.Ticket != null);
  13. //认证cookie校验认证上下文的方法
  14. var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket);
  15. await Events.ValidatePrincipal(context);
  16. if (context.Principal == null)
  17. {
  18. return AuthenticateResults.NoPrincipal;
  19. }
  20. //判断上下文中的ShouldRenew参数,判断是否刷新Cookie
  21. if (context.ShouldRenew)
  22. {
  23. RequestRefresh(result.Ticket, context.Principal);
  24. }
  25. return AuthenticateResult.Success(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name));
  26. }
  27. //读取Cookie
  28. private async Task<AuthenticateResult> ReadCookieTicket()
  29. {
  30. //读取客户端存在的cookie信息.
  31. var cookie = Options.CookieManager.GetRequestCookie(Context, Options.Cookie.Name!);
  32. if (string.IsNullOrEmpty(cookie))
  33. {
  34. return AuthenticateResult.NoResult();
  35. }
  36. //解密Cookie内容
  37. var ticket = Options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
  38. if (ticket == null)
  39. {
  40. return AuthenticateResults.FailedUnprotectingTicket;
  41. }
  42. //如果配置了SessionStore,可以进行持久化管理,
  43. if (Options.SessionStore != null)
  44. {
  45. // 拿到seesionId的cliam
  46. var claim = ticket.Principal.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
  47. if (claim == null)
  48. {
  49. return AuthenticateResults.MissingSessionId;
  50. }
  51. // Only store _sessionKey if it matches an existing session. Otherwise we'll create a new one.
  52. ticket = await Options.SessionStore.RetrieveAsync(claim.Value, Context, Context.RequestAborted);
  53. if (ticket == null)
  54. {
  55. return AuthenticateResults.MissingIdentityInSession;
  56. }
  57. _sessionKey = claim.Value;
  58. }
  59. var currentUtc = TimeProvider.GetUtcNow();
  60. var expiresUtc = ticket.Properties.ExpiresUtc;
  61. //cookie过期检测
  62. if (expiresUtc != null && expiresUtc.Value < currentUtc)
  63. {
  64. if (Options.SessionStore != null)
  65. {
  66. await Options.SessionStore.RemoveAsync(_sessionKey!, Context, Context.RequestAborted);
  67. // Clear out the session key if its expired, so renew doesn't try to use it
  68. _sessionKey = null;
  69. }
  70. return AuthenticateResults.ExpiredTicket;
  71. }
  72. // Finally we have a valid ticket
  73. return AuthenticateResult.Success(ticket);
  74. }
  75. // 检查并且刷新
  76. private async Task CheckForRefreshAsync(AuthenticationTicket ticket)
  77. {
  78. var currentUtc = TimeProvider.GetUtcNow();
  79. var issuedUtc = ticket.Properties.IssuedUtc;
  80. var expiresUtc = ticket.Properties.ExpiresUtc;
  81. var allowRefresh = ticket.Properties.AllowRefresh ?? true;
  82. if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration && allowRefresh)
  83. //Options.SlidingExpiration 和allowRefresh控制是否自动刷新
  84. {
  85. var timeElapsed = currentUtc.Subtract(issuedUtc.Value);
  86. var timeRemaining = expiresUtc.Value.Subtract(currentUtc);
  87. var eventContext = new CookieSlidingExpirationContext(Context, Scheme, Options, ticket, timeElapsed, timeRemaining)
  88. {
  89. ShouldRenew = timeRemaining < timeElapsed,
  90. };
  91. await Events.CheckSlidingExpiration(eventContext);
  92. if (eventContext.ShouldRenew)
  93. {
  94. //请求刷新
  95. RequestRefresh(ticket);
  96. }
  97. }
  98. }

基于 Jwt 的方式实现

https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer?view=aspnetcore-8.0

JWT简介

  • https://jwt.io/

  • JWT是JSON Web Token的简称,是一个开放标准,用于在各方之间安全地传输信息。

  • JWT通常用于用户认证和信息交换。由于它是数字签名的,所以信息可以验证和信任

JWT由三部分组成,分别是Header(头部)、Payload(负载)和Signature(签名),它们之间用点(.)分隔。

  • Header(头部):包含了两部分信息,即所使用的签名算法(如HMAC SHA256或RSA)和Token的类型(通常是JWT)。例如:{"alg":"HS256","typ":"JWT"}。这个JSON对象会被Base64Url编码以形成JWT的第一部分。
  • Payload(负载):包含了要传输的声明(Claims)。这些声明是关于实体(通常是用户)和其他数据的声明。声明有三种类型:Registered Claims(注册声明)、Public Claims(公共声明)和Private Claims(私有声明)。例如:{"sub":"123","name":"Tom","admin":true}。这个JSON对象也会被Base64Url编码以形成JWT的第二部分。
  • Signature(签名):是将Header、Payload和密钥(Key)通过指定算法(HMAC、RSA)进行加密生成的。例如,HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload), secret)。这个签名就是JWT的第三部分。

JWT的工作原理

  • 用户向服务器发送用户名和密码。
  • 服务器验证这些信息后,会生成一个JWT,并将其作为响应返回给用户。
  • 用户将JWT保存在本地(如浏览器的cookie中),并在后续的请求中将其发送给服务器。
  • 服务器验证JWT的有效性(如签名是否正确、Token是否过期等),如果验证通过,则允许用户访问资源。

JWT的优势

  • 去中心化:JWT的数据保存在各个客户端而不是服务器,降低了服务器的负担。
  • 可扩展性:由于JWT是自包含的,因此可以在多个系统之间轻松实现单点登录。
  • 安全性:JWT使用了数字签名,可以确保信息的完整性和有效性。

使用场景

JWT常用于用户认证、单点登录、信息交换等场景。由于其紧凑、自包含和可验证的特性,JWT在现代Web应用中得到了广泛的应用。

定义JWT加解密类

  1. public class JWTTokenOptions
  2. {
  3. public string Audience { get; set; }
  4. public string SecurityKey { get; set; }
  5. public string Issuer { get; set; }
  6. }
  7. public interface IJWTService
  8. {
  9. /// <summary>
  10. /// 新版本
  11. /// </summary>
  12. /// <param name="userInfo"></param>
  13. /// <returns></returns>
  14. string GetTokenWithModel(User userInfo);
  15. /// <summary>
  16. /// 获取Token+RefreshToken
  17. /// </summary>
  18. /// <param name="userInfo"></param>
  19. /// <returns>Token+RefreshToken</returns>
  20. Tuple<string, string> GetTokenWithRefresh(User userInfo);
  21. /// <summary>
  22. /// 基于refreshToken获取Token
  23. /// </summary>
  24. /// <param name="refreshToken"></param>
  25. /// <returns></returns>
  26. string GetTokenByRefresh(string refreshToken);
  27. }
  28. public class JWTService: IJWTService
  29. {
  30. private static Dictionary<string, User> TokenCache = new Dictionary<string, User>();
  31. private JWTTokenOptions _JWTTokenOptions = null;
  32. public JWTService(IOptions<JWTTokenOptions> options)
  33. {
  34. this._JWTTokenOptions = options.Value;
  35. }
  36. /// <summary>
  37. /// 刷新token的有效期问题上端校验
  38. /// </summary>
  39. /// <param name="refreshToken"></param>
  40. /// <returns></returns>
  41. public string GetTokenByRefresh(string refreshToken)
  42. {
  43. //refreshToken在有效期,但是缓存可能没有? 还能去手动清除--比如改密码了,清除缓存,用户来刷新token就发现没有了,需要重新登陆
  44. if (TokenCache.ContainsKey(refreshToken))
  45. {
  46. string token = this.IssueToken(TokenCache[refreshToken], 60);
  47. return token;
  48. }
  49. else
  50. {
  51. return "";
  52. }
  53. }
  54. /// <summary>
  55. /// 2个token 就是有效期不一样
  56. /// </summary>
  57. /// <param name="userInfo"></param>
  58. /// <returns></returns>
  59. public Tuple<string, string> GetTokenWithRefresh(User userInfo)
  60. {
  61. string token = this.IssueToken(userInfo, 60);//1分钟
  62. string refreshToken = this.IssueToken(userInfo, 60 * 60 * 24 * 7);//7*24小时
  63. TokenCache.Add(refreshToken, userInfo);
  64. return Tuple.Create(token, refreshToken);
  65. }
  66. public string GetTokenWithModel(User userModel)
  67. {
  68. //return this.IssueToken(userModel);
  69. return this.IssueToken(userModel, 1);
  70. }
  71. private string IssueToken(User userModel, int second = 600)
  72. {
  73. var claims = new[]
  74. {
  75. new Claim(ClaimTypes.Name, userModel.UserName),
  76. new Claim(ClaimTypes.Email, userModel.Email),
  77. new Claim(ClaimTypes.Role,userModel.Role),
  78. };
  79. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._JWTTokenOptions.SecurityKey));
  80. var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  81. /**
  82. * Claims (Payload)
  83. Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:
  84. iss: The issuer of the token,token 是给谁的
  85. sub: The subject of the token,token 主题
  86. exp: Expiration Time。 token 过期时间,Unix 时间戳格式
  87. iat: Issued At。 token 创建时间, Unix 时间戳格式
  88. jti: JWT ID。针对当前 token 的唯一标识
  89. 除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
  90. * */
  91. var token = new JwtSecurityToken(
  92. issuer: this._JWTTokenOptions.Issuer,
  93. audience: this._JWTTokenOptions.Audience,
  94. claims: claims,
  95. expires: DateTime.Now.AddSeconds(second),//10分钟有效期
  96. notBefore: DateTime.Now,//立即生效 DateTime.Now.AddMilliseconds(30),//30s后有效
  97. signingCredentials: creds);
  98. string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
  99. return returnToken;
  100. }
  101. }
  102. /// <summary>
  103. /// 用户类
  104. /// </summary>
  105. public class User
  106. {
  107. public string UserName { get; set; }
  108. public string Email { get; set; }
  109. public string Role { get; set; }
  110. }

定义JWT验证方案

定义JWTTokenOptions

  1. "JWTTokenOptions": {
  2. "Audience": "http://localhost:5555",
  3. "Issuer": "http://localhost:5555",
  4. "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
  5. }

builder.Services 中,你需要定义你的自定义身份验证方案,并配置相关的处理程序。这可以通过 AddAuthenticationAddScheme 方法来完成。

  1. //配置JWTTokenOptions
  2. builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
  3. builder.Services.AddTransient<IJWTService, JWTService>();
  4. JWTTokenOptions tokenOptions = new JWTTokenOptions();
  5. builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
  6. builder.Services.AddAuthentication(x =>
  7. {
  8. x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  9. x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  10. }).AddJwtBearer(options =>
  11. {
  12. options.TokenValidationParameters = new TokenValidationParameters
  13. {
  14. ValidateIssuer = true,//是否验证Issuer
  15. ValidateAudience = true, //是否验证Audience
  16. ValidateLifetime = true, //是否验证失效时间
  17. ValidateIssuerSigningKey = true, //是否验证SecurityKey
  18. ValidAudience = tokenOptions.Audience, //订阅人Audience
  19. ValidIssuer = tokenOptions.Issuer,//发行人Issuer
  20. ClockSkew = TimeSpan.FromSeconds(60), //特别注意:默认是5分钟缓冲,过期时间容错值,解决服务器端时间不同步问题(秒)
  21. RequireExpirationTime = true,
  22. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)) //SecurityKey
  23. };
  24. //options.Events = new JwtBearerEvents
  25. //{
  26. // OnAuthenticationFailed = async (context) =>
  27. // {
  28. // await context.Response.WriteAsJsonAsync(
  29. // new
  30. // {
  31. // Result = false,
  32. // Message = context?.Exception?.Message
  33. // });
  34. // // await Task.CompletedTask;
  35. // },
  36. // OnTokenValidated = async (context) =>
  37. // {
  38. // //await context.Response.WriteAsJsonAsync(
  39. // // new
  40. // // {
  41. // // Result = false,
  42. // // Message = context?.Result?.Failure?.Message
  43. // // });
  44. // await Console.Out.WriteLineAsync(context?.Result?.Failure?.Message);
  45. // },
  46. // OnChallenge = async (context) =>
  47. // {
  48. // await context.Response.WriteAsJsonAsync(
  49. // new
  50. // {
  51. // Result = false,
  52. // Message = context?.AuthenticateFailure?.Message
  53. // });
  54. // },
  55. // OnForbidden = async (context) =>
  56. // {
  57. // await context.Response.WriteAsJsonAsync(
  58. // new
  59. // {
  60. // Result = false,
  61. // Message = context?.Result?.Failure?.Message
  62. // });
  63. // },
  64. // OnMessageReceived = async (context) =>
  65. // {
  66. // await Console.Out.WriteLineAsync(context?.Result?.Failure?.Message);
  67. // //await context.Response.WriteAsJsonAsync(
  68. // // new
  69. // // {
  70. // // Result = false,
  71. // // Message = context?.Result?.Failure?.Message
  72. // // });
  73. // }
  74. //};
  75. })
  76. ;

TokenValidationParameters 类用于配置 JWT(JSON Web Tokens)的验证参数。以下是这个类中的一些常用属性

  1. ValidIssuer
    • 类型:string
    • 描述:预期的发行者(Issuer)值。如果令牌中的发行者与此值不匹配,则令牌验证将失败。
  2. ValidIssuers
    • 类型:IEnumerable<string>
    • 描述:预期的发行者列表。如果令牌中的发行者在此列表中,则令牌验证将成功。
  3. ValidAudience
    • 类型:string
    • 描述:预期的受众(Audience)值。如果令牌中的受众与此值不匹配,则令牌验证将失败。
  4. ValidAudiences
    • 类型:IEnumerable<string>
    • 描述:预期的受众列表。如果令牌中的受众在此列表中,则令牌验证将成功。
  5. IssuerSigningKey
    • 类型:SecurityKey
    • 描述:用于验证令牌签名的安全密钥。这通常是一个 SymmetricSecurityKey(用于 HMACSHA 系列算法)或 RsaSecurityKey(用于 RSA 算法)。
  6. IssuerSigningKeys
    • 类型:IEnumerable<SecurityKey>
    • 描述:用于验证令牌签名的安全密钥列表。这允许在验证过程中使用多个密钥。
  7. ValidateIssuerSigningKey
    • 类型:bool
    • 描述:一个标志,指示是否应验证发行者签名密钥。默认值为 true
  8. ValidateIssuer
    • 类型:bool
    • 描述:一个标志,指示是否应验证发行者。默认值为 true
  9. ValidateAudience
    • 类型:bool
    • 描述:一个标志,指示是否应验证受众。默认值为 true
  10. ValidateLifetime
    • 类型:bool
    • 描述:一个标志,指示是否应验证令牌的生命周期(即 expnbf 声明)。默认值为 true
  11. ClockSkew
    • 类型:TimeSpan
    • 描述:用于处理由于时钟偏差而导致的时间差。当验证令牌的 expnbf 声明时,此值将被考虑在内。默认值为 5 分钟。
  12. RequireExpirationTime
    • 类型:bool
    • 描述:一个标志,指示是否应要求令牌具有过期时间(exp 声明)。默认值为 false
  13. RequireSignedTokens
    • 类型:bool
    • 描述:一个标志,指示是否应要求令牌是签名的。默认值为 true
  14. SaveSigningKey
    • 类型:bool
    • 描述:一个标志,指示是否应将签名密钥保存到缓存中,以便在后续请求中重用。默认值为 false
  15. TokenDecryptionKey
    • 类型:SecurityKey
    • 描述:用于解密令牌的密钥(如果令牌是加密的)。
  16. TokenDecryptionKeys
    • 类型:IEnumerable<SecurityKey>
    • 描述:用于解密令牌的密钥列表(如果令牌是加密的)。
  17. ValidateTokenReplay
    • 类型:bool
    • 描述:一个标志,指示是否应验证令牌是否已经被使用过(即重放攻击)。这不是 TokenValidationParameters 类中的内置属性,但可以通过自定义逻辑实现。

JwtBearerEvents 类提供了一组事件,这些事件可以在 JWT 承载令牌认证过程中被触发,以便你可以添加自定义逻辑。以下是 JwtBearerEvents 类中的一些常用事件

  1. OnAuthenticationFailed
    • 描述:当身份验证失败时触发。这通常发生在 JWT 令牌验证不通过、签名不匹配或过期时,可以使用此事件进行错误记录、自定义错误响应或执行其他逻辑。
  2. OnChallenge
    • 描述:当需要挑战(即返回 401 Unauthorized 响应)客户端以提供认证凭据时触发。这通常发生在需要认证但请求中没有包含有效令牌的情况下。你可以在这个事件处理器中修改挑战响应,比如添加额外的头部信息或自定义错误消息。
  3. OnMessageReceived
    • 描述:在令牌从请求中读取之前触发。你可以在这个事件处理器中自定义令牌的读取逻辑,比如从自定义的请求头或查询字符串中获取令牌。
  4. OnTokenValidated
    • 描述:在令牌验证成功之后但在创建 ClaimsIdentity 之前触发。你可以在这个事件处理器中添加或修改用户的声明(Claims)。
  5. OnForbidden
    • 描述:当资源被授权但用户没有访问权限时触发(例如,用户没有足够的角色或权限),可以使用此事件记录禁止访问的事件或发送自定义的禁止访问响应。

配置中间件

Startup.Configure 方法中,确保 UseAuthentication 中间件被添加到请求处理管道中。

  1. //鉴权 (核心源码就是AuthenticationMiddleware中间件)
  2. app.UseAuthentication();
  3. //授权 使用Authorize必须配置app.UseAuthorization();
  4. app.UseAuthorization();

测试认证

在你的应用程序代码中,你可以通过 HttpContext.AuthenticateAsync 方法来触发认证流程。但是,在大多数情况下,认证是在中间件级别自动处理的

  1. /// <summary>
  2. /// http://localhost:5555/Auth/JWTLogin?name=admin&password=123456
  3. /// </summary>
  4. /// <param name="name"></param>
  5. /// <param name="password"></param>
  6. /// <returns></returns>
  7. public async Task<IActionResult> JWTLogin(string name, string password)
  8. {
  9. if ("admin".Equals(name, StringComparison.CurrentCultureIgnoreCase)
  10. && password.Equals("123456"))//等同于去数据库校验
  11. {
  12. User user = new User
  13. {
  14. UserName = name,
  15. Email = "2545233857@qq.com",
  16. Role = "admin",
  17. };
  18. var token = _jwtService.GetTokenWithModel(user);
  19. return new JsonResult(new
  20. {
  21. Result = true,
  22. token = token,
  23. Message = "登录成功"
  24. });
  25. }
  26. else
  27. {
  28. await Task.CompletedTask;
  29. return new JsonResult(new
  30. {
  31. Result = false,
  32. Message = "登录失败"
  33. });
  34. }
  35. }
  36. /// <summary>
  37. /// http://localhost:5555/Auth/JWTToken
  38. /// </summary>
  39. /// <returns></returns>
  40. //[Authorize] //使用Authorize必须配置app.UseAuthorization();
  41. public async Task<IActionResult> JWTToken()
  42. {
  43. var userOrigin = base.HttpContext.User;
  44. var result = await base.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
  45. if (result?.Principal == null)
  46. {
  47. return new JsonResult(new
  48. {
  49. Result = false,
  50. Message = result?.Failure?.Message ?? $"认证失败,用户未登录"
  51. });
  52. }
  53. else
  54. {
  55. base.HttpContext.User = result.Principal;
  56. StringBuilder sb = new StringBuilder();
  57. foreach (var item in base.HttpContext.User.Identities.First().Claims)
  58. {
  59. Console.WriteLine($"Claim {item.Type}:{item.Value}");
  60. }
  61. return new JsonResult(new
  62. {
  63. Result = true,
  64. Message = $"认证成功,用户已登录"
  65. });
  66. }
  67. }

image

image

源码

https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/JwtBearer/src/JwtBearerHandler.cs

  1. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  2. {
  3. string? token;
  4. try
  5. {
  6. // Give application opportunity to find from a different location, adjust, or reject token
  7. var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);
  8. // event can set the token
  9. //发布消息订阅
  10. await Events.MessageReceived(messageReceivedContext);
  11. if (messageReceivedContext.Result != null)
  12. {
  13. return messageReceivedContext.Result;
  14. }
  15. // If application retrieved token from somewhere else, use that.
  16. token = messageReceivedContext.Token;
  17. if (string.IsNullOrEmpty(token))
  18. {
  19. //获取authorization
  20. string authorization = Request.Headers.Authorization.ToString();
  21. // If no authorization header found, nothing to process further
  22. if (string.IsNullOrEmpty(authorization))
  23. {
  24. return AuthenticateResult.NoResult();
  25. }
  26. //获取token
  27. if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
  28. {
  29. token = authorization.Substring("Bearer ".Length).Trim();
  30. }
  31. // If no token found, no further work possible
  32. if (string.IsNullOrEmpty(token))
  33. {
  34. return AuthenticateResult.NoResult();
  35. }
  36. }
  37. var tvp = await SetupTokenValidationParametersAsync();
  38. List<Exception>? validationFailures = null;
  39. SecurityToken? validatedToken = null;
  40. ClaimsPrincipal? principal = null;
  41. //不使用SecurityToken验证器
  42. if (!Options.UseSecurityTokenValidators)
  43. {
  44. foreach (var tokenHandler in Options.TokenHandlers)
  45. {
  46. try
  47. {
  48. //验证token
  49. var tokenValidationResult = await tokenHandler.ValidateTokenAsync(token, tvp);
  50. if (tokenValidationResult.IsValid)
  51. {
  52. principal = new ClaimsPrincipal(tokenValidationResult.ClaimsIdentity);
  53. validatedToken = tokenValidationResult.SecurityToken;
  54. break;
  55. }
  56. else
  57. {
  58. validationFailures ??= new List<Exception>(1);
  59. RecordTokenValidationError(tokenValidationResult.Exception ?? new SecurityTokenValidationException($"The TokenHandler: '{tokenHandler}', was unable to validate the Token."), validationFailures);
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. validationFailures ??= new List<Exception>(1);
  65. RecordTokenValidationError(ex, validationFailures);
  66. }
  67. }
  68. }
  69. else
  70. {
  71. #pragma warning disable CS0618 // Type or member is obsolete
  72. foreach (var validator in Options.SecurityTokenValidators)
  73. {
  74. if (validator.CanReadToken(token))
  75. {
  76. try
  77. {
  78. //验证token
  79. principal = validator.ValidateToken(token, tvp, out validatedToken);
  80. }
  81. catch (Exception ex)
  82. {
  83. validationFailures ??= new List<Exception>(1);
  84. RecordTokenValidationError(ex, validationFailures);
  85. continue;
  86. }
  87. }
  88. }
  89. #pragma warning restore CS0618 // Type or member is obsolete
  90. }
  91. //判断凭证和token
  92. if (principal != null && validatedToken != null)
  93. {
  94. Logger.TokenValidationSucceeded();
  95. var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
  96. {
  97. Principal = principal
  98. };
  99. tokenValidatedContext.SecurityToken = validatedToken;
  100. tokenValidatedContext.Properties.ExpiresUtc = GetSafeDateTime(validatedToken.ValidTo);
  101. tokenValidatedContext.Properties.IssuedUtc = GetSafeDateTime(validatedToken.ValidFrom);
  102. //发布Token验证成功事件
  103. await Events.TokenValidated(tokenValidatedContext);
  104. if (tokenValidatedContext.Result != null)
  105. {
  106. return tokenValidatedContext.Result;
  107. }
  108. if (Options.SaveToken)
  109. {
  110. tokenValidatedContext.Properties.StoreTokens(new[]
  111. {
  112. new AuthenticationToken { Name = "access_token", Value = token }
  113. });
  114. }
  115. tokenValidatedContext.Success();
  116. return tokenValidatedContext.Result!;
  117. }
  118. //验证失败结果
  119. if (validationFailures != null)
  120. {
  121. var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
  122. {
  123. Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
  124. };
  125. //发布验证失败事件
  126. await Events.AuthenticationFailed(authenticationFailedContext);
  127. if (authenticationFailedContext.Result != null)
  128. {
  129. return authenticationFailedContext.Result;
  130. }
  131. return AuthenticateResult.Fail(authenticationFailedContext.Exception);
  132. }
  133. if (!Options.UseSecurityTokenValidators)
  134. {
  135. return AuthenticateResults.TokenHandlerUnableToValidate;
  136. }
  137. return AuthenticateResults.ValidatorNotFound;
  138. }
  139. catch (Exception ex)
  140. {
  141. Logger.ErrorProcessingMessage(ex);
  142. var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
  143. {
  144. Exception = ex
  145. };
  146. //发布验证失败事件
  147. await Events.AuthenticationFailed(authenticationFailedContext);
  148. if (authenticationFailedContext.Result != null)
  149. {
  150. return authenticationFailedContext.Result;
  151. }
  152. throw;
  153. }
  154. }

基于自定义的方式实现

定义自定义身份验证方案

builder.Services 中,你需要定义你的自定义身份验证方案,并配置相关的处理程序。这可以通过 AddAuthenticationAddScheme 方法来完成。

  1. builder.Services.AddAuthentication(options =>
  2. {
  3. options.AddScheme<XTokenAuthenticationHandler2>(XTokenAuthenticationDefaults.AuthenticationScheme, "");
  4. options.DefaultAuthenticateScheme = XTokenAuthenticationDefaults.AuthenticationScheme;
  5. options.DefaultChallengeScheme = XTokenAuthenticationDefaults.AuthenticationScheme;
  6. options.DefaultSignInScheme = XTokenAuthenticationDefaults.AuthenticationScheme;
  7. options.DefaultForbidScheme = XTokenAuthenticationDefaults.AuthenticationScheme;
  8. options.DefaultSignOutScheme = XTokenAuthenticationDefaults.AuthenticationScheme;
  9. });

实现自定义身份验证处理器

你需要创建一个类,实现 IAuthenticationHandler 接口或继承 AuthenticationHandler<TOptions> 类(其中 TOptions 是你的认证选项类),并在这个类中实现你的自定义认证逻辑。

  1. /// <summary>
  2. /// DES加解密
  3. /// </summary>
  4. public class DesEncrypt
  5. {
  6. private static byte[] key = Encoding.UTF8.GetBytes("1234567812345678"); // 16字节的密钥
  7. private static byte[] iv = Encoding.UTF8.GetBytes("1234567812345678"); // 16字节的初始化向量
  8. /// <summary>
  9. /// 加密
  10. /// </summary>
  11. /// <param name="plainText"></param>
  12. /// <returns></returns>
  13. public static string Encrypt(string plainText)
  14. {
  15. using (Aes aes = Aes.Create())
  16. {
  17. aes.Key = key;
  18. aes.IV = iv;
  19. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
  20. using (MemoryStream ms = new MemoryStream())
  21. {
  22. using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
  23. {
  24. using (StreamWriter sw = new StreamWriter(cs))
  25. {
  26. sw.Write(plainText);
  27. }
  28. }
  29. return Convert.ToBase64String(ms.ToArray());
  30. }
  31. }
  32. }
  33. /// <summary>
  34. /// 解密
  35. /// </summary>
  36. /// <param name="cipherText"></param>
  37. /// <returns></returns>
  38. public static string Decrypt(string cipherText)
  39. {
  40. using (Aes aes = Aes.Create())
  41. {
  42. aes.Key = key;
  43. aes.IV = iv;
  44. ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
  45. byte[] bytes = Convert.FromBase64String(cipherText);
  46. using (MemoryStream ms = new MemoryStream(bytes))
  47. {
  48. using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
  49. {
  50. using (StreamReader sr = new StreamReader(cs))
  51. {
  52. return sr.ReadToEnd();
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// 用户类
  61. /// </summary>
  62. public class User
  63. {
  64. public string UserName { get; set; }
  65. public string Email { get; set; }
  66. public string Role { get; set; }
  67. }

基于IAuthenticationHandler 接口

  1. public class XTokenAuthenticationHandler : IAuthenticationHandler
  2. {
  3. private AuthenticationScheme _authenticationScheme;
  4. private HttpContext _httpContext;
  5. private string _tokenName = "x-token";
  6. private ILogger<XTokenAuthenticationHandler> _logger;
  7. public XTokenAuthenticationHandler(ILogger<XTokenAuthenticationHandler> logger)
  8. {
  9. _logger = logger;
  10. }
  11. public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
  12. {
  13. _authenticationScheme = scheme;
  14. _httpContext = context;
  15. return Task.CompletedTask;
  16. }
  17. public Task<AuthenticateResult> AuthenticateAsync()
  18. {
  19. try
  20. {
  21. if (_httpContext.Request.Headers.ContainsKey(_tokenName))
  22. {
  23. string token = _httpContext.Request.Headers[_tokenName];
  24. var userStr = DesEncrypt.Decrypt(token);
  25. var userInfo = JsonConvert.DeserializeObject<User>(userStr);
  26. //校验---整理信息,保存起来
  27. var claimIdentity = new ClaimsIdentity("Custom");
  28. claimIdentity.AddClaim(new Claim(ClaimTypes.Name, userInfo.UserName));
  29. claimIdentity.AddClaim(new Claim(ClaimTypes.Role, userInfo.Role));
  30. claimIdentity.AddClaim(new Claim(ClaimTypes.Email, userInfo.Email));
  31. ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimIdentity);//信息拼装和传递
  32. return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, null, _authenticationScheme.Name)));
  33. }
  34. else
  35. {
  36. return Task.FromResult(AuthenticateResult.NoResult());//没有凭证
  37. }
  38. }
  39. catch (Exception ex)
  40. {
  41. _logger.LogError(ex, ex.Message);
  42. return Task.FromResult(AuthenticateResult.Fail($"认证失败请重新登录"));
  43. }
  44. }
  45. /// <summary>
  46. /// 未登录
  47. /// </summary>
  48. /// <param name="properties"></param>
  49. /// <returns></returns>
  50. public Task ChallengeAsync(AuthenticationProperties? properties)
  51. {
  52. _httpContext.Response.StatusCode = 401;
  53. //_httpContext.Response.WriteAsJsonAsync(new
  54. //{
  55. // Result = false,
  56. // Message = !string.IsNullOrEmpty(_errorMessage) ? _errorMessage : "认证失败,请重新登录"
  57. //}) ;
  58. return Task.CompletedTask;
  59. }
  60. /// <summary>
  61. /// 未授权,无权限
  62. /// </summary>
  63. /// <param name="properties"></param>
  64. /// <returns></returns>
  65. public Task ForbidAsync(AuthenticationProperties? properties)
  66. {
  67. _httpContext.Response.StatusCode = 403;
  68. //_httpContext.Response.WriteAsJsonAsync(new
  69. //{
  70. // Result = false,
  71. // Message = "访问失败,未授权"
  72. //});
  73. return Task.CompletedTask;
  74. }
  75. }
  76. public class XTokenAuthenticationDefaults
  77. {
  78. /// <summary>
  79. /// 提供固定名称
  80. /// </summary>
  81. public const string AuthenticationScheme = "XTokenScheme";
  82. }

基于继承 AuthenticationHandler<TOptions>

  1. public class XTokenAuthenticationHandler2 : AuthenticationHandler<AuthenticationSchemeOptions>
  2. {
  3. private string _tokenName = "x-token";
  4. private ILogger<XTokenAuthenticationHandler2> _logger;
  5. public XTokenAuthenticationHandler2(ILogger<XTokenAuthenticationHandler2> logger1, IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
  6. {
  7. _logger = logger1;
  8. }
  9. /// <summary>
  10. /// 认证
  11. /// </summary>
  12. /// <returns></returns>
  13. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  14. {
  15. try
  16. {
  17. if (Request.Headers.ContainsKey(_tokenName))
  18. {
  19. string token = Request.Headers[_tokenName];
  20. var userStr = DesEncrypt.Decrypt(token);
  21. var userInfo = JsonConvert.DeserializeObject<User>(userStr);
  22. //校验---整理信息,保存起来
  23. var claimIdentity = new ClaimsIdentity("Custom");
  24. claimIdentity.AddClaim(new Claim(ClaimTypes.Name, userInfo.UserName));
  25. claimIdentity.AddClaim(new Claim(ClaimTypes.Role, userInfo.Role));
  26. claimIdentity.AddClaim(new Claim(ClaimTypes.Email, userInfo.Email));
  27. ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimIdentity);//信息拼装和传递
  28. return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, null, Scheme.Name)));
  29. }
  30. else
  31. {
  32. return Task.FromResult(AuthenticateResult.NoResult());//没有凭证
  33. }
  34. }
  35. catch (Exception ex)
  36. {
  37. _logger.LogError(ex, ex.Message);
  38. return Task.FromResult(AuthenticateResult.Fail($"认证失败请重新登录"));
  39. }
  40. }
  41. }

配置中间件

Startup.Configure 方法中,确保 UseAuthentication 中间件被添加到请求处理管道中。

  1. //鉴权 (核心源码就是AuthenticationMiddleware中间件)
  2. app.UseAuthentication();

测试认证

在你的应用程序代码中,你可以通过 HttpContext.AuthenticateAsync 方法来触发认证流程。但是,在大多数情况下,认证是在中间件级别自动处理的

  1. /// <summary>
  2. /// http://localhost:5555/Auth/XTokenLogin?name=admin&password=123456
  3. /// </summary>
  4. /// <param name="name"></param>
  5. /// <param name="password"></param>
  6. /// <returns></returns>
  7. public async Task<IActionResult> XTokenLogin(string name, string password)
  8. {
  9. if ("admin".Equals(name, StringComparison.CurrentCultureIgnoreCase)
  10. && password.Equals("123456"))//等同于去数据库校验
  11. {
  12. User user = new User
  13. {
  14. UserName = name,
  15. Email = "2545233857@qq.com",
  16. Role = "admin",
  17. };
  18. var token = DesEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(user));
  19. return new JsonResult(new
  20. {
  21. Result = true,
  22. token = token,
  23. Message = "登录成功"
  24. });
  25. }
  26. else
  27. {
  28. await Task.CompletedTask;
  29. return new JsonResult(new
  30. {
  31. Result = false,
  32. Message = "登录失败"
  33. });
  34. }
  35. }
  36. /// <summary>
  37. /// http://localhost:5555/Auth/XToken
  38. /// </summary>
  39. /// <returns></returns>
  40. //没有要求授权
  41. public async Task<IActionResult> XToken()
  42. {
  43. var userOrigin = base.HttpContext.User;
  44. var result = await base.HttpContext.AuthenticateAsync(XTokenAuthenticationDefaults.AuthenticationScheme);
  45. if (result?.Principal == null)
  46. {
  47. return new JsonResult(new
  48. {
  49. Result = false,
  50. Message = $"认证失败,用户未登录"
  51. });
  52. }
  53. else
  54. {
  55. base.HttpContext.User = result.Principal;
  56. StringBuilder sb = new StringBuilder();
  57. foreach (var item in base.HttpContext.User.Identities.First().Claims)
  58. {
  59. Console.WriteLine($"Claim {item.Type}:{item.Value}");
  60. }
  61. return new JsonResult(new
  62. {
  63. Result = true,
  64. Message = $"认证成功,用户已登录"
  65. });
  66. }
  67. }

image

源码

https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs

  1. /// <summary>
  2. /// Extension methods to add authentication capabilities to an HTTP application pipeline.
  3. /// </summary>
  4. public static class AuthAppBuilderExtensions
  5. {
  6. public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app)
  7. {
  8. return app.UseMiddleware<AuthenticationMiddleware>();
  9. }
  10. }
  11. public class AuthenticationMiddleware
  12. {
  13. public async Task Invoke(HttpContext context)
  14. {
  15. //其它...
  16. var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
  17. if (defaultAuthenticate != null)
  18. {
  19. //验证
  20. var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
  21. if (result?.Principal != null)
  22. {
  23. //赋值
  24. context.User = result.Principal;
  25. }
  26. if (result?.Succeeded ?? false)
  27. {
  28. var authFeatures = new AuthenticationFeatures(result);
  29. context.Features.Set<IHttpAuthenticationFeature>(authFeatures);
  30. context.Features.Set<IAuthenticateResultFeature>(authFeatures);
  31. }
  32. }
  33. await _next(context);
  34. }
  35. }

原文链接:https://www.cnblogs.com/vic-tory/p/18237065

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号