Dropbox REST API In .NET WebApplication - Getting The Request Token And Access Token

Dropbox, one of the most used and advanced file sharing web application nowadays, that gives you the freedom to use your files anywhere online and offline. I was just wondering that if there is a way to access the files I have in my Dropbox from .NET web application.

I googled it and did not find much resources to achieve this. But I got to know that yes Dropbox provides REST API for accessing your files, folders form your application (PHP, Java, Python, Ruby). But unfortunately it does not provide any support for .NET applications.

But it does not mean that we can not do this ;)

Here is a way I find out to access Dropbox from .NET web application. Here in this article I will be explaining you how to get the access token and access token secret using Dropbox rest API.




Download Source Code Here
   

Let's Get the Request Token and Access Token


First of all you need to create an app in the Dropbox which will yield an app key and an app secret. Those two are necessary while authorizing your app by the users, who are going to use your web application.

So, you can create an app here Dropbox . Create it and have your key and secret ready with you.


Dropbox uses the OAuth 2.0 authorization. A user interacts with your app via this OAuth 2.0 and decides whether he want to grant access to your app or not. Once the user grant access to your app then you can access all most everything of that user in your web application.

 N.B: You have to set the accessibility of your app while creating it; I mean what are the things your app will be able to access of the user.

OK, lets start with our codding stuffs from here.

Create a web application in your visual studio. and then add this OAuthBase.cs to it (Download OAuthBase.cs), we will be using this call for all type of authorization calls.

Dropbox provides 3 type of Urito use its API;

Base uri: https://api.dropbox.com/
Authorize Base Uri: https://www.dropbox.com/
Api Content Server: https://api-content.dropbox.com/

Here we will be using the first 2 Uri for getting the access token and then for authorization.

N.B: Download the source code for better understanding from the above link.

Now lets jump to the .net project we have created just 2 min before. Add the below controls to the Default.aspx page, where you have to enter your app key and the app secret to get the access tokens.

Enter your consumer key :
    <asp:TextBox ID="txtConsumerKey" runat="server"></asp:TextBox><br />
    <br />
    Enter your consumer secret :
    <asp:TextBox ID="txtConsumerSecret" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Button" OnClick="btnSubmit_Click" />
    <br />
    <br />
    Here is your access token :
    <asp:Label ID="lblAccessToken" runat="server"></asp:Label><br />
    <br />
    Enter your access token secret :
    <asp:Label ID="lblAccessTokenSecret" runat="server"></asp:Label>

Request Token


Now go to the code behind and Create a method named GetRequestToken(). We will be getting the request token here. Here in this method we are creating a signature for the OAuth API call and then creating a request URL, that will be called in order to get the request tokens from Dropbox.


Below are the costants and the global variables you need to declare first.
private const string authorizeUri = "https://www.dropbox.com/1/oauth/authorize?";
 private const string dropBoxApiUri = "https://api.dropbox.com/1/oauth/";
 private static string consumerKey = string.Empty;
 private static string consumerSecret = string.Empty;

 private class OAuthToken
     {
         public OAuthToken(string token, string secret)
         {
             Token = token;
             Secret = secret;
         }

         public string Token { get; private set; }

         public string Secret { get; private set; }
     }
Then set the app key and app secret to the global variables in the button click event.

//Set the consumer secret and consumer key.
    consumerKey = txtConsumerKey.Text.Trim();
    consumerSecret = txtConsumerSecret.Text.Trim();
Here is the method to get the request token GetRequestToken();

/// <summary>
 /// Gets the request token and secret.
 /// </summary>
 /// <returns></returns>
 private static OAuthToken GetRequestToken()
 {
     var uri =  new Uri(dropBoxApiUri + "request_token");

     // Generate a signature
     OAuthBase oAuth = new OAuthBase();
     string nonce = oAuth.GenerateNonce();
     string timeStamp = oAuth.GenerateTimeStamp();
     string parameters;
     string normalizedUrl;
     string signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret,
         String.Empty, String.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
         out normalizedUrl, out parameters);

     // Encode the signature
     signature = HttpUtility.UrlEncode(signature);

     // Now buld the url by appending the consumer key, secret timestamp and all.
     StringBuilder requestUri = new StringBuilder(uri.ToString());
     requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
     requestUri.AppendFormat("oauth_nonce={0}&", nonce);
     requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
     requestUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
     requestUri.AppendFormat("oauth_version={0}&", "1.0");
     requestUri.AppendFormat("oauth_signature={0}", signature);

     // createa request to call the dropbox api.
     WebRequest request = WebRequest.Create(new Uri(requestUri.ToString()));
     request.Method = WebRequestMethods.Http.Get;

     // Get the response.
     WebResponse response = request.GetResponse();

     // Read the response
     string queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();

     var parts = queryString.Split('&');
     string token = parts[1].Substring(parts[1].IndexOf('=') + 1);
     string secret = parts[0].Substring(parts[0].IndexOf('=') + 1);

     return new OAuthToken(token, secret);
 }
after the call you will get a url like below;

https://api.dropbox.com/1/oauth/request_token?oauth_consumer_key=99z93238p60auz7&oauth_nonce=4121576&oauth_timestamp=1388236733&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=vYQktpEvTnsG2H1qqsYjlNcVNbU%3d

Authorization


Once you have got the request token then you need to authorize your app by the user. And the request token will be used in the authorization process. Add the below code to the button click event for the authorization.
// Authorize application
 string queryString = String.Format("oauth_token={0}", oauthToken.Token);
 string authorizeUrl = authorizeUri + queryString;

 // Start the process and Leave some time for the authorization step to complete
 Process.Start(authorizeUrl);
 Thread.Sleep(5000); 

Access Token


Once authorization complete, you can call the API exactly same as before we did for the access tokens. For this I have created a method named GetAccessToken(), that takes the request token as input.
/// <summary>
 /// Gets the access token by the request token and the token secret.
 /// </summary>
 /// <param name="oauthToken"></param>
 /// <returns></returns>
 private static OAuthToken GetAccessToken(OAuthToken oauthToken)
 {

     var uri =  new Uri(dropBoxApiUri + "access_token");

     OAuthBase oAuth = new OAuthBase();

     // Generate a signature
     var nonce = oAuth.GenerateNonce();
     var timeStamp = oAuth.GenerateTimeStamp();
     string parameters;
     string normalizedUrl;
     var signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret,
         oauthToken.Token, oauthToken.Secret, "GET", timeStamp, nonce,
         OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters);

     // Encode the signature
     signature = HttpUtility.UrlEncode(signature);

     // Now buld the url by appending the consumer key, secret timestamp and all.
     var requestUri = new StringBuilder(uri.ToString());
     requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
     requestUri.AppendFormat("oauth_token={0}&", oauthToken.Token);
     requestUri.AppendFormat("oauth_nonce={0}&", nonce);
     requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
     requestUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
     requestUri.AppendFormat("oauth_version={0}&", "1.0");
     requestUri.AppendFormat("oauth_signature={0}", signature);

     // createa request to call the dropbox api.
     WebRequest request = WebRequest.Create(requestUri.ToString());
     request.Method = WebRequestMethods.Http.Get;

     // Get the response.
     WebResponse response = request.GetResponse();

     // Read the response
     StreamReader reader = new StreamReader(response.GetResponseStream());
     string accessToken = reader.ReadToEnd();

     var parts = accessToken.Split('&');
     string token = parts[1].Substring(parts[1].IndexOf('=') + 1);
     string secret = parts[0].Substring(parts[0].IndexOf('=') + 1);

     return new OAuthToken(token, secret);
 }
Now print the two access token and token secret. Once you got the access token, you are all set to do all the manipulations like accessing the user account information, files, folders, creating/deleting/moving folders, uploading/downloading files.


I will be explaining how to get the account info of the user in my next article using these access tokens we got from here.


Happy Coding...

11 comments:

  1. Sir, Your article on Drop box API is very helpful for me. Thanks

    ReplyDelete
  2. Ahaa, its nice conversation concerning this paragraph here at this
    web site, I have read all that, so at this time
    me also commenting at this place.

    My website: boiler engineers

    ReplyDelete
  3. Howdy, i read your blog occasionally and i own a
    similar one and i was just curious if you get a lot of spam responses?

    If so how do you reduce it, any plugin or anything you can advise?
    I get so much lately it's driving me mad so any assistance is very
    much appreciated.

    Also visit my website ... ,mobile lawn mower repair Clackamas Oregon,

    ReplyDelete
  4. It's a shame you don't have a donate button!
    I'd without a doubt donate to this brilliant blog!
    I suppose for now i'll settle for book-marking and adding your RSS feed to
    my Google account. I look forward to new updates and will share this website
    with my Facebook group. Talk soon!

    Feel free to visit my weblog car accident

    ReplyDelete
  5. Thanks a lot for your valuable tutorials.
    Sir, I want to get all file in dropbox, in a list form in my web application?
    please guide me

    ReplyDelete
    Replies
    1. Hi, thanks for your appreciation, Can I know what type of help you need ?

      Delete
  6. Thanks a lot for your feedback sir
    I create a web application and I want to add a cloud service like dropbox. I am able to get token_id and token_secret from above code.
    Now I want to access all files present on dropbox and show all file in my web application .

    ReplyDelete
    Replies
    1. Yeah I got it, I can help you out on this. Please drop me an email from this link so that we can discuss and solve your problem.

      http://www.thecybria.com/contact

      Thanks

      Delete