Question

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

  • 22 October 2015
  • 5 replies
  • 4128 views

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.


5 replies

Hey Todd,

There is an unofficial C# SDK available here which might be of help: https://github.com/grokify/ringcentral-sdk-csharp-simple

There are examples for just obtaining the RingCentral SDK Client, and a simple example for sending an SMS message once you've authenticated.
I downloaded the sample project from the link you provided me and when I run the code it says "Access Expired". Please advise. Thank you for all your help.
Can you share the Response Message ? And what is the HTTP status code? 
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.
Thanks for sharing this Todd...great help.

Love seeing the use of async in there that makes a ton of sense in addition to setting this up as a worker.

Reply