Beispiel #1
0
        /// <summary>
        /// Internally sets the current service configuration without validation. This is used
        /// with the default constructor so that the user can specify a configuration using the
        /// ServiceConfig property without forcing a validation (because the default config is
        /// invalid without a credential).
        /// </summary>
        private void SetServiceConfigInternal(EmsApiServiceConfiguration config)
        {
            m_config = config;
            m_clientHandler.ServiceConfig = config;

            // Reset the default headers, they may have changed with the config.
            m_httpClient.DefaultRequestHeaders.Clear();
            m_config.AddDefaultRequestHeaders(m_httpClient.DefaultRequestHeaders);

            // See if the endpoint has changed.
            if (m_config.Endpoint != m_endpoint)
            {
                m_endpoint = m_config.Endpoint;

                // Reset the BaseAddress, and create a new refit service stub.
                // It's bound to the HttpClient's base address when it's constructed.
                m_httpClient.BaseAddress = new Uri(m_config.Endpoint);
                RefitApi = RestService.For <IEmsApi>(m_httpClient);
            }
        }
        private bool GetNewBearerToken(out string error, CancellationToken?cancel = null)
        {
            error = null;

            var request = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}/token", m_serviceConfig.Endpoint));

            m_serviceConfig.AddDefaultRequestHeaders(request.Headers);

            request.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "grant_type", SecurityConstants.GrantTypePassword },
                { "username", m_serviceConfig.UserName },
                { "password", m_serviceConfig.Password }
            });

            CancellationToken   cancelToken = cancel ?? new CancellationToken();
            HttpResponseMessage response    = base.SendAsync(request, cancelToken).Result;

            // Regardless of if we succeed or fail the call, the returned structure will be a chunk of JSON.
            string rawResult = response.Content.ReadAsStringAsync().Result;
            var    result    = JObject.Parse(rawResult);

            if (!response.IsSuccessStatusCode)
            {
                string description = result.GetValue("error_description").ToString();
                error = string.Format("Unable to retrieve EMS API bearer token: {0}", description);
                return(false);
            }

            string token     = result.GetValue("access_token").ToString();
            int    expiresIn = result.GetValue("expires_in").ToObject <int>();

            // Stash the new token and keep track of when we expire.
            m_authToken       = token;
            m_tokenExpiration = DateTime.UtcNow.AddSeconds(expiresIn);
            return(true);
        }