400 Bad Request when using authorization code flow and exchanging code for token

  • 1
  • Problem
  • Updated 3 years ago
  • Not a Problem
Hello! I'm working on a site that's currently trying to integrate with RingCentral's API. We have multiple customers that will be using the API, so we're going with the Authorization Code Flow. We're able to redirect the user over to RingCentral and have them authorize their account, but when trying to exchange the received code, we receive a 400 error.

The site is an MVC5 app and I haven't been able to find any examples of the authorization code flow for this type of application, but maybe I haven't looked far enough. Below is the bit of code that tries to make the exchange for the access/refresh tokens:

            WebRequest request = WebRequest.Create($"{AppConfig.Settings.RingCentral.ApiEndpoint}/restapi/oauth/token");
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.Method = "POST";
request.Headers["Authorization"] = $"Basic {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{AppConfig.Settings.RingCentral.AppKey}:{AppConfig.Settings.RingCentral.AppSecret}"))}";

string body = $"grant_type=authorization_code;code={code};redirect_uri={AppConfig.Settings.General.RootPublicUrl}/OAuthCallback/RingCentralToken;";

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(body);
request.ContentLength = bytes.Length;

using (var stream = request.GetRequestStream())
stream.Write(bytes, 0, bytes.Length);

using (var response = request.GetResponse()) //400 Bad Request here
//get tokens from response here
I feel like I'm doing something obviously wrong here, but I can't seem to figure out what that is. If I need to give more information, let me know!
Photo of John Keene

John Keene

  • 100 Points 100 badge 2x thumb

Posted 3 years ago

  • 1
Photo of John Wang

John Wang, Official Rep

  • 5,826 Points 5k badge 2x thumb
Official Response
The master branch of the C# SDK has Authorization Code flow support now which you can see below:


There's also an example using the existing C# SDK release here:


Let us know if those help!
Photo of John Keene

John Keene

  • 100 Points 100 badge 2x thumb
I wasn't aware of that, thank you! The provided C# example does the trick. Thanks for the help!