123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using ZXing.Aztec.Internal;
- namespace HTEXMark
- {
- public static class HttpClientHelper
- {
- public static async Task<(HttpClient httpClient,string AuthorizationToken,bool ok)> CheckToken (string AuthorizationToken,string domian ,string X_Auth_Authtoken, HttpClient httpClient)
- {
- bool ok = false;
- long now =DateTimeOffset.Now.ToUnixTimeSeconds();
- var jwt = new JwtSecurityToken(AuthorizationToken);
- if (!httpClient.DefaultRequestHeaders.Contains("X-Auth-Authtoken"))
- {
- httpClient.DefaultRequestHeaders.Add("X-Auth-Authtoken", X_Auth_Authtoken);
- }
- if (jwt.Payload.Expiration.HasValue && jwt.Payload.Expiration.Value>now)
- {
- if (httpClient.DefaultRequestHeaders.Contains("Authorization"))
- {
- httpClient.DefaultRequestHeaders.Remove("Authorization");
- }
- httpClient.DefaultRequestHeaders.Add("Authorization",$"Bearer {AuthorizationToken}" );
- ok = true;
- }
- else {
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
- string url = $"https://{domian}/hita/refresh-access-token";
- var response = await httpClient.PostAsJsonAsync(url, new Dictionary<string, string> { { "refresh-token", AuthorizationToken } });
- if (response.IsSuccessStatusCode) {
- string content = await response.Content.ReadAsStringAsync();
- JsonElement json = JsonSerializer.Deserialize<JsonElement>(content);
- if (json.TryGetProperty("code", out JsonElement _code)&& $"{_code}".Equals("200") && json.TryGetProperty("access_token", out JsonElement _access_token)) {
- AuthorizationToken= _access_token.GetString();
- if (httpClient.DefaultRequestHeaders.Contains("Authorization")) {
- httpClient.DefaultRequestHeaders.Remove("Authorization");
- }
- httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {AuthorizationToken}");
- ok = true;
- }
- }
- }
- return (httpClient, AuthorizationToken,ok);
- }
- }
- }
|