BasicAuthenticationHandler.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using Microsoft.AspNetCore.Authentication;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Http.Features;
  5. using Microsoft.Extensions.Logging;
  6. using Microsoft.Extensions.Options;
  7. using System.Net.Http.Headers;
  8. using System.Security.Claims;
  9. using System.Text.Encodings.Web;
  10. using XYY.Core.Standard.Data.Infrastructure;
  11. using XYY.Core.Standard.Mvc;
  12. public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOption>
  13. {
  14. private readonly IUnitOfWork unitOfWork;
  15. public BasicAuthenticationHandler(
  16. IOptionsMonitor<BasicAuthenticationOption> options,
  17. ILoggerFactory logger,
  18. UrlEncoder encoder,
  19. ISystemClock clock,
  20. IUnitOfWork unitOfWork)
  21. : base(options, logger, encoder, clock)
  22. {
  23. this.unitOfWork = unitOfWork;
  24. }
  25. public Endpoint? GetEndpoint(HttpContext context)
  26. {
  27. if (context == null)
  28. {
  29. return null;
  30. }
  31. return context.Features.Get<IEndpointFeature>()?.Endpoint;
  32. }
  33. /// <summary>
  34. /// 认证 Token
  35. /// </summary>
  36. /// <returns></returns>
  37. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  38. {
  39. bool isAllow = false;
  40. var endpoint = GetEndpoint(this.Context);
  41. if (endpoint != null)
  42. {
  43. var allow = endpoint.Metadata.GetMetadata<IAllowAnonymous>();
  44. if (allow != null)
  45. {
  46. isAllow = true;
  47. }
  48. }
  49. if (isAllow || Request.Path.Value.Contains("dingtalk") || Request.Path.Value.Contains("SendNowCustomerQuotaion", StringComparison.InvariantCultureIgnoreCase))
  50. {
  51. var claims = new[]
  52. {
  53. new Claim(ClaimTypes.StreetAddress,""),
  54. };
  55. var identity = new ClaimsIdentity(claims, Scheme.Name);
  56. var principal = new ClaimsPrincipal(identity);
  57. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  58. unitOfWork.CurrentName = "";
  59. return await Task.FromResult(AuthenticateResult.Success(ticket));
  60. }
  61. if (!Request.Headers.ContainsKey("Authorization"))
  62. {
  63. if (string.IsNullOrEmpty(Request.Query["access_token"]))
  64. {
  65. return AuthenticateResult.Fail("Missing Authorization ");
  66. }
  67. }
  68. try
  69. {
  70. string token = "";
  71. //var uservice = Context.RequestServices.GetService<IUserService>();
  72. if (Request.Headers.ContainsKey("Authorization"))
  73. {
  74. var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
  75. //var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
  76. if (!authHeader.Scheme.Equals("token", StringComparison.InvariantCultureIgnoreCase)
  77. && !authHeader.Scheme.Equals("bearer", StringComparison.InvariantCultureIgnoreCase))
  78. {
  79. return AuthenticateResult.Fail("Invalid Token");
  80. }
  81. else
  82. {
  83. token = authHeader.Parameter;
  84. }
  85. }
  86. else
  87. {
  88. token = Request.Query["access_token"];
  89. }
  90. var user = await Authorized(token);
  91. if (user != null)
  92. {
  93. ///当前用户的身份信息
  94. var claims = new[]
  95. {
  96. new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
  97. new Claim(ClaimTypes.Name,user.Name),
  98. new Claim(ClaimTypes.StreetAddress,token),
  99. new Claim(ClaimTypes.GivenName,user.CustomeCompanyName??""),
  100. new Claim(ClaimTypes.GroupSid,user.CustomerId.ToString()),
  101. new Claim(ClaimTypes.Role,string.Join(",",user.RoleNames)),
  102. new Claim(ClaimTypes.AuthorizationDecision,string.Join(",",user.Permissions.Select(x=>x.Url)))
  103. };
  104. var identity = new ClaimsIdentity(claims, Scheme.Name);
  105. var principal = new ClaimsPrincipal(identity);
  106. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  107. unitOfWork.CurrentName = user.Name;
  108. unitOfWork.CurrentId = user.CustomerId;
  109. return await Task.FromResult(AuthenticateResult.Success(ticket));
  110. }
  111. else
  112. {
  113. return AuthenticateResult.Fail("token无效");
  114. }
  115. }
  116. catch
  117. {
  118. return AuthenticateResult.Fail("Invalid Authorization Header");
  119. }
  120. }
  121. /// <summary>
  122. /// 质询
  123. /// </summary>
  124. /// <param name="properties"></param>
  125. /// <returns></returns>
  126. protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
  127. {
  128. //Response.Headers["WWW-Authenticate"] = $"Basic realm=our site";
  129. await base.HandleChallengeAsync(properties);
  130. }
  131. /// <summary>
  132. /// 认证失败
  133. /// </summary>
  134. /// <param name="properties"></param>
  135. /// <returns></returns>
  136. protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
  137. {
  138. await base.HandleForbiddenAsync(properties);
  139. }
  140. private async Task<UserInfo> Authorized(string token)
  141. {
  142. System.Net.WebClient client = new System.Net.WebClient();
  143. client.BaseAddress = "http://120.24.149.148:9500/";
  144. client.Headers.Add("Content-Type", "application/json; charset=utf-8");
  145. client.Headers.Add("Authorization", "token 132A7468DE079C6CEB59F383A661E612");
  146. try
  147. {
  148. var response = client.UploadString("/api/auth/GetUserInfoAsToken?token=" + token, "");
  149. var u = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiJsonModel<UserInfo>>(response);
  150. if (u.success)
  151. {
  152. return u.data;
  153. }
  154. else
  155. {
  156. throw new Exception("鉴权失败" + u.message);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. throw new Exception("登陆失败" + ex.Message);
  162. }
  163. }
  164. }