Exemplo n.º 1
0
        private static void WriteTokenToCache(string resource, AuthorizationToken token)
        {
            byte[] data;
            string tokenData;

            try
            {
                tokenData = JsonConvert.SerializeObject(token);
                data      = _protector.Protect(System.Text.Encoding.Default.GetBytes(tokenData));
                tokenData = Convert.ToBase64String(data);

                _cache.Write(GetKey(resource), tokenData, token.ExpiresOn.AddMinutes(-1).TimeOfDay);
            }
            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;
            }
        }