Exemplo n.º 1
0
        public async Task <TokenObj> AuthenticateAsync(string username, string password)
        {
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("username", username),
                new KeyValuePair <string, string>("password", password),
            });

            var url = $"{TokenServer}/{TokenAuthAction}";

            if (!this.DefaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
            {
                this.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }

            var resp = await this.PostAsync(url, content);

            if (resp.IsSuccessStatusCode)
            {
                AuthTokenResult = await resp.Content.ReadAsAsync <TokenObj>();

                this.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                         AuthTokenResult.access_token);
                return(AuthTokenResult);
            }
            else
            {
                var cnt = await resp.Content.ReadAsStringAsync();

                var exMsg = $"StatusCode:{resp.StatusCode} - {resp.ReasonPhrase} - {cnt}";
                var err   = new { Content = cnt, Message = exMsg };
                throw new AuthenticationException($"Unable to authenticate with {url} - Message:\n{exMsg}");
            }
        }
Exemplo n.º 2
0
 public BearerTokenAuthClientHandler(TokenObj tokenObj)
 {
     _authToken = tokenObj;
 }