Search code examples
c#-4.0box-api

Authentication for Box in C# 4.0


I'm trying to get the access token using the below code in C# language, but I'm getting 400 bad request exception.

Code:

WebRequest httpWReq = WebRequest.Create("https://www.box.com/api/oauth2/token");


string postData = "grant_type=authorization_code"; 
postData += "&code=" + Code; 
postData += "&client_id=MY_CLIENT_ID"; 
postData += "&client_secret=MY_CLIENT_SECRET"; 
postData += "&redirect_uri=https://www.google.com";

byte[] data = Encoding.UTF8.GetBytes(postData); 
httpWReq.Method = "POST"; 
httpWReq.ContentType = "application/x-www-form-urlencoding"; 
httpWReq.ContentLength = data.Length; 

using (Stream stream = httpWReq.GetRequestStream()) 
{ 
    stream.Write(data, 0, data.Length); 
}

var response = httpWReq.GetResponse();
var responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
    var responseReader = reader.ReadToEnd();
    MessageBox.Show(responseReader);
}

But I'm always getting the following Error:

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

How to overcome this problem?

Any Help will be appreciated. Thanks in Advance.

Thanks, Harish Reddy


Solution

  • I see two possible problems, both with this line:

    postData += "&redirect_uri=https://www.google.com";
    
    1. I think you'll need to urlencode the redirect URI.
    2. I presume you don't own the google.com domain, so that's an invalid value. :) You'll need to point back to the domain from which you're making the request. Or better yet, preset this redirect URI on your Box app's configuration page.

    Incidentally, you may be interested in checking out the Box API v2 SDK for .Net (and corresponding MVC-based OAuth example) that are up on GitHub and NuGet. (Full disclosure: I contribute to both.)