Anyone have any C# sample code to authenicate to the API and make some requests?

  • 1
  • Question
  • Updated 3 years ago
  • Answered
Not sure how to do Oauth2 authentication to a web API in C#. If anyone has done so already, could please share some sample code, so I don't have to re-invent the wheel.
Photo of Todd

Todd

  • 230 Points 100 badge 2x thumb

Posted 3 years ago

  • 1
Photo of Todd

Todd

  • 230 Points 100 badge 2x thumb
Official Response
Today I finally got the answer my original question. The code snippet below.


    public class Worker
    {
        private static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        private string _accessToken;
       
       public async void WaitForAuthToken()
        {
            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new System.Uri($"{Settings.ServerUrl}restapi/oauth/token"),
                    Method = HttpMethod.Post,
                };
                 request.Headers.TryAddWithoutValidation("Content-Type", @"application/x-www-form-urlencoded;charset=UTF-8");
                request.Headers.Add("Authorization", $"Basic {Base64Encode($"{Settings.AppKey}:{Settings.AppSecret}")}"); 
                request.Content = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", Settings.PhoneNumber),
                new KeyValuePair<string, string>("password", Settings.Password),
                new KeyValuePair<string, string>("extension", Settings.Extension)
            });

                var response = await client.SendAsync(request);
                var responseContent = await response.Content.ReadAsStringAsync();
                var d = (dynamic) Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent);
                _accessToken = d.access_token;
            }
        }
    }




Simple really.