using FHT.Agency.Web.Utility; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; namespace FHT.Agency.Web.CommandServices { public class AuthorizationService { private const string userName = "15850745912"; private const string password = "gaohongzhi"; private const double PERCENT = 0.8; private readonly HttpClient _httpClient; public AuthorizationService() { _httpClient = new HttpClient { BaseAddress = new Uri(AgentApplicationEnvironment.FhtApiHost) }; } public string Login() { var parameters = new Dictionary(); string accessTokenCached = CacheHelper.GetCache("access_token"); string expiresInCached = CacheHelper.GetCache("expires_in"); string refreshTokenCached = CacheHelper.GetCache("refresh_token"); string refreshTokenExpireCached = CacheHelper.GetCache("expires"); double effectiveMinutes = ApplicationConfig.AccessTokenExpireTimeSpan.TotalMinutes; bool isRefreshToken = !string.IsNullOrEmpty(refreshTokenCached) && !string.IsNullOrEmpty(refreshTokenExpireCached) && Convert.ToDateTime(refreshTokenExpireCached) > DateTime.Now; bool isAccessTokenInCache = !string.IsNullOrEmpty(expiresInCached) && !string.IsNullOrEmpty(accessTokenCached) && Convert.ToDateTime(expiresInCached) >= DateTime.Now.AddMinutes(effectiveMinutes * PERCENT); if (isAccessTokenInCache) { return accessTokenCached; } if (isRefreshToken) { parameters.Add("refresh_token", refreshTokenCached); parameters.Add("grant_type", "refresh_token"); } else { parameters.Add("username", userName); parameters.Add("password", password); parameters.Add("grant_type", "password"); } string result = _httpClient.PostAsync("/Token", new FormUrlEncodedContent(parameters)).Result.Content.ReadAsStringAsync().Result; //result 中含有“.expires”、“.issued”属性,无法使用DeserializeObject反序列化 JObject jobject = JObject.Parse(result); if (jobject["access_token"] == null) { throw new InvalidOperationException("access_token not found in json"); } DateTime expires_in = Convert.ToDateTime(jobject[".expires"]); string accessToken = jobject["access_token"].ToString(); CacheHelper.SetCache("access_token", accessToken); CacheHelper.SetCache("expires_in", expires_in); bool isCacheRefreshToken = string.IsNullOrEmpty(refreshTokenExpireCached) || Convert.ToDateTime(refreshTokenExpireCached) <= DateTime.Now || (Convert.ToDateTime(refreshTokenExpireCached) - expires_in).TotalMinutes <= effectiveMinutes; if (isCacheRefreshToken) { CacheHelper.SetCache("refresh_token", jobject["refresh_token"].ToString()); CacheHelper.SetCache("expires", ApplicationConfig.RefreshTokenExpireAt); } return accessToken; } } }