private static AuthorizationToken GetTokenFromCache(string resource) { AuthorizationToken authToken; byte[] data; string token; try { if (!_cache.KeyExists(GetKey(resource))) { return(null); } data = _protector.Unprotect(Convert.FromBase64String(_cache.Read(GetKey(resource)))); token = System.Text.Encoding.Default.GetString(data); authToken = JsonConvert.DeserializeObject <AuthorizationToken>(token); return(!authToken.IsNearExpiry() ? authToken : null); } finally { data = null; } }
private async Task <IPartnerCredentials> GetPartnerCenterTokenAsync() { AuthenticationResult authResult; IPartnerCredentials credentials; byte[] data; string token; try { if (_cache.KeyExists(Key)) { data = _protector.Unprotect(Convert.FromBase64String(_cache.Read(Key))); token = System.Text.Encoding.Default.GetString(data); credentials = JsonConvert.DeserializeObject <PartnerCenterToken>(token); if (!credentials.IsExpired()) { return(credentials); } } authResult = await TokenContext.GetAADTokenAsync( $"{AppConfig.Authority}/{AppConfig.AccountId}/oauth2", AppConfig.PartnerCenterApiUri); credentials = await PartnerCredentials.Instance.GenerateByUserCredentialsAsync(AppConfig.ApplicationId, new AuthenticationToken(authResult.AccessToken, authResult.ExpiresOn)); token = JsonConvert.SerializeObject(credentials); data = _protector.Protect(System.Text.Encoding.Default.GetBytes(token)); token = Convert.ToBase64String(data); _cache.Write(Key, token, credentials.ExpiresAt.AddMinutes(-1).TimeOfDay); return(credentials); } finally { authResult = null; data = null; } }