HttpClientHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using ZXing.Aztec.Internal;
  11. namespace HTEXMark
  12. {
  13. public static class HttpClientHelper
  14. {
  15. public static async Task<(HttpClient httpClient,string AuthorizationToken,bool ok)> CheckToken (string AuthorizationToken,string domian ,string X_Auth_Authtoken, HttpClient httpClient)
  16. {
  17. bool ok = false;
  18. long now =DateTimeOffset.Now.ToUnixTimeSeconds();
  19. var jwt = new JwtSecurityToken(AuthorizationToken);
  20. if (!httpClient.DefaultRequestHeaders.Contains("X-Auth-Authtoken"))
  21. {
  22. httpClient.DefaultRequestHeaders.Add("X-Auth-Authtoken", X_Auth_Authtoken);
  23. }
  24. if (jwt.Payload.Expiration.HasValue && jwt.Payload.Expiration.Value>now)
  25. {
  26. if (httpClient.DefaultRequestHeaders.Contains("Authorization"))
  27. {
  28. httpClient.DefaultRequestHeaders.Remove("Authorization");
  29. }
  30. httpClient.DefaultRequestHeaders.Add("Authorization",$"Bearer {AuthorizationToken}" );
  31. ok = true;
  32. }
  33. else {
  34. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  35. string url = $"https://{domian}/hita/refresh-access-token";
  36. var response = await httpClient.PostAsJsonAsync(url, new Dictionary<string, string> { { "refresh-token", AuthorizationToken } });
  37. if (response.IsSuccessStatusCode) {
  38. string content = await response.Content.ReadAsStringAsync();
  39. JsonElement json = JsonSerializer.Deserialize<JsonElement>(content);
  40. if (json.TryGetProperty("code", out JsonElement _code)&& $"{_code}".Equals("200") && json.TryGetProperty("access_token", out JsonElement _access_token)) {
  41. AuthorizationToken= _access_token.GetString();
  42. if (httpClient.DefaultRequestHeaders.Contains("Authorization")) {
  43. httpClient.DefaultRequestHeaders.Remove("Authorization");
  44. }
  45. httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {AuthorizationToken}");
  46. ok = true;
  47. }
  48. }
  49. }
  50. return (httpClient, AuthorizationToken,ok);
  51. }
  52. }
  53. }