Dropbox REST API Part 1: Authentication

December 29, 2011

IntroductionDropBox Logo

I’ve been using Dropbox for about 6 months now. Before that I relied on Google Documents to share my files between the computers I use. Of course I had to login first and then I had to download them. Kind of a drag, certainly with big files.

With Dropbox that’s a thing of the past. Just install the client software and it will synchronize all of your files automatically. They are neatly downloaded into a local Dropbox folder on each of your computers. And only the parts of the file that actually changed are transferred, greatly reducing the download time.

Another neat feature is that other applications can use your Dropbox folder to store their data. For instance, I use a password manager (AgileBit’s 1Password) to securely save my login accounts. If I create a new account for a site on my laptop, then when I start my desktop it will automatically be known there once Dropbox has synched 1Password’s files (which is nearly instantanously).

This is made possible thanks to the Dropbox REST API. Let’s find out how we can use it…

Table Of Contents

My Apps

Before you can start, you first need to register your application with Dropbox. To do so, please follow these steps:

  • Login to Dropbox
  • Click on the link “Developers” which is displayed on the bottom (center) of the page
  • Click on the link “My Apps” displayed in the menu on the left side
  • Now click on the button “Create an App”

Create an App

Choose a unique name for your application and select the appropriate access rights. You can lock your application in its own folder or you can grant it access to your entire Dropbox folder. Usually users don’t want to grant third-party applications access to their entire Dropbox folder so it’s best to choose the “App folder” option. However, since this is a demo I’ve choosen the “Full Dropbox” option. It will come in handy for later parts of this series.

Dropbox Application

Click Create to register your application. After you have created an application you’ll get two tokens, namely an app key and a secret. Here are mine (don’t worry…I’ve already deleted my app when you are reading this).

App Key and Secret

Keep those tokens nearby. You’ll need them when signing in to Dropbox.

Top of page

Request Token

Dropbox offers several SDKs for their REST API. Android, iOS, Java, Python and Ruby are all supported. Unfortunately there is no SDK for the .NET framework. Odd if you ask me, but not that big of an issue. There are some third party SDKs available, but let’s do the basic plumbling ourselves. A bit more work to do, but we’ll get there.

Before you can use the REST API you need to go through the authentication process. Dropbox requires that all requests are done over SSL and it uses OAuth to authenticate all of the API requests.

After you have completed the authentication process you’ll have an access token and access token secret. You can then use the access token for all the other requests. The authentication process consists out of three steps:

  1. Request token: Obtain an OAuth request token to be used for the rest of the authentication process.
  2. Authorize: The user must grant your application access to their Dropbox.
  3. Access token: Once your application is authorized you can acquire an access token.

Let’s start by obtaining an OAuth request token. Start Visual Studio 2010 and create a new blank solution called Dropbox. Next add a console application to the solution titled ConsoleApplication. Coming up with original names, it’s important.

Solution Explorer

To quickly support OAuth I’ve downloaded a small, usefull library called OAuth. You can download it here:

http://code.google.com/p/oauth/

Download the C# version, it’s a single file (OAuthBase.cs) and add it to the console application project.

OAuthBase.cs

To request an OAuth request token you need to send a request to https://api.dropbox.com/1/oauth/request_token. You need to include the following parameters:

  • oauth_consumer_key: Your API key
  • oauth_nonce: A number used only once
  • oauth_timestamp: Timestamp of the request
  • oauth_signature_method: Signature method
  • oauth_signature: Signature of the request. A hash to sign the request based on a couple of parameters.
  • oauth_version: OAuth version used

There are no Dropbox specific parameters required for this request. Using the OAuth library you downloaded earlier this is pretty straightforward. First let’s generate a signature for the request.

var consumerKey = "your api key";
var consumerSecret = "your api secret";

var uri = new Uri("https://api.dropbox.com/1/oauth/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);

signature = HttpUtility.UrlEncode(signature);

You’ll wind up with a weird looking string like zwct8VZ469%2bLpmi9C8%2fVpghpk7w%3d. Now let’s issue the actual request.

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);

var request = (HttpWebRequest) WebRequest.Create(new Uri(requestUri.ToString()));
request.Method = WebRequestMethods.Http.Get;

var response = request.GetResponse();

Here we compose the URL including all the parameters (query string) and then we issue the request. Your URL should resemble the following pattern:

https://api.dropbox.com/1/oauth/request_token?oauth_consumer_key=your api key&oauth_nonce=9328214&oauth_timestamp=1325081302&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=OskIFg2iOhcVJ2qHGDN6VDXxUik%3d

Just make sure to use your own API (or consumer) key and secret. Let’s parse the response which includes a request token and request token secret. For instance:

oauth_token_secret=bdifrgl4si3if8w&oauth_token=cny4z2vkqpbqd6k

var response = request.GetResponse();

var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();

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

Voila, using this crude “Hello, World”-ish code you can now complete step 1 of the authentication process. You now have a token and token secret which you can use to complete the authentication process.

Top of page

Authorize

Once you have an OAuth request token and secret it’s very simple to authorize your application. You only need to send a request to:

https://www.dropbox.com/1/oauth/authorize

This request only requires one parameter, namely the request token you obtained earlier.

  • oauth_token: the OAuth request token

Resulting in a URL which looks like this:

https://www.dropbox.com/1/oauth/authorize?oauth_token=yourtoken

Let’s start the authorization process:

var queryString = String.Format("oauth_token={0}", token);
var authorizeUrl = "https://www.dropbox.com/1/oauth/authorize?" + queryString;
Process.Start(authorizeUrl);

This will open a new browser window. You’ll be asked to login to Dropbox. Once you have done so you can choose if you want to grant (authorize) your first Dropbox application access to your Dropbox folder.

Authorize Dropbox Application

Once you click on Allow the application will be added to the list of applications which can access your Dropbox. You can view this list in the My Apps section in your account. You can always revoke the access at a later time.

My Apps

Top of page

Access Token

By now you have an OAuth access token and you have authorized your application so that it can access your Dropbox folder. Time to finish the authentication process. After the authorization step is complete you can acquire an access token.

This access token is needed to authenticate all the API requests. Once you have obtained such a token you can store it and reuse it later. You don’t need to go through the authentication process again. Just make sure to store the token securely, because it is required for all access to the user’s Dropbox folder.

Acquiring an access token is very similar to the first step. You must send a request to https://api.dropbox.com/1/oauth/access_token, including the following parameters:

  • oauth_consumer_key: Your API key
  • oauth_token: The OAuth token you obtained in step 1
  • oauth_nonce: A number used only once
  • oauth_timestamp: Timestamp of the request
  • oauth_signature_method: Signature method
  • oauth_signature: Signature of the request. A hash to sign the request based on a couple of parameters.
  • oauth_version: OAuth version used

First let’s generate a signature for this request.

var consumerKey = "your api key";
var uri = "https://api.dropbox.com/1/oauth/access_token";

OAuthBase oAuth = new OAuthBase();

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

signature = HttpUtility.UrlEncode(signature);

Now you can send the request.

var requestUri = new StringBuilder(uri);
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);

var request = (HttpWebRequest) WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Get;

Parsing the response will give you a return value which resembles this:

oauth_token_secret=95grkd9na7hm&oauth_token=ccl4li5n1q9b

var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();

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

You now have an access token and corresponding access token secret. The authentication process is now complete and you can use the access token and secret to sign requests for the main API calls.

Remark: Make sure to leave some time between step 2 and 3, so that the authorization step can succeed. You need to redirect the user to Dropbox so that they can authorize your application. You need to wait until the user has completed this step.

In part 2 of this series I’ll show you some examples of how you can use the acess token and secret to access the main Dropbox REST API.

I’ll try to get the next part online as soon as possible. You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.

Top of page

About these ads

53 Responses to “Dropbox REST API Part 1: Authentication”

  1. sandeep sharma Says:

    good


  2. Awesome!! Thank you!!

  3. cap Says:

    I get an error at this line, of the GetAccessToken:

    var response = request.GetResponse();

    403. Forbidden.

    • cap Says:

      Sorry i have not read everything properly, so if i am using a Web Browser Component, what would be the best away of starting step 3? How can i can i start it after the app has been allowed by the user?

      • Christophe Says:

        Cap, take a look at the Dropbox REST API documentation under the /authorize section.

        https://www.dropbox.com/developers/reference/api

        During the second step you can specify an optional parameter called oauth_callback. This is a URL which you pass when authorizing the user. After the authorization has completed Dropbox will redirect the user to this URL. This way you are notified when the authorization has completed. Afterwards you can start step 3.

        Another option is to have the user indicate that the authorization has been completed. However, this is less intuitive.

        Regards,

        Christophe

  4. cap Says:

    Thanks for the answer. I have solve the problem by asking the user when the authorization process is completed.

    I am looking forward for the 3 part of this tutorial.

  5. Martin Tobón Says:

    This is not working for me… When I click “Allow” in the dropbox page after the login step, the app doesn’t appear in the list of applications in the account section… I’m receiving also a 403 error when trying to get the access token.

    ¿Do you guys have some ideas?.. I’m running the code downloaded from this site…

    I have an app in development status and the dropbox account is the 2GB.

    Cheers

    • Christophe Says:

      If you could mail me your code I’ll have a look this weekend.

      • Martin Tobón Says:

        It’s the same code posted on the downloads page… i just added the keys provided by dropbox after creating an app.

        I can give you those keys if you want to… where can i check your mail?

    • Christophe Says:

      geersch@gmail.com ….. could be that you leave too little time between step 2 and 3 …

      • Martin Tobón Says:

        No, i put a Console.ReadLine(); in order to press a key when the Allow process is finished…

      • Martin Tobón Says:

        Thanks god man!! I finally got it!!… it looks like you’ve got to request for the access token in order for the application to appear in My Apps under account.

        Thank you for your help!!

        I Really apreciate that

        By the way man, what a great blog you’ve got!

    • Christophe Says:

      Tip: paste the request URLs in a browser. When trying to get a request token (step 1) for your application I receive a 403 error. Just examine the response while debugging or paste the request URL in a browser. You’ll get more information. In your case, Dropbox tells met that your application has been disabled, so the 403 error (Forbidden) makes sense.

      Response:

      {“error”: “This app has been disabled.”}

  6. testo Says:

    You should use PLAINTEXT signature method, makes things much easier.

  7. srinivas Says:

    This worked so well with Windows 8 metro too, with few changes to oauthBase.cs. Great article!

  8. smee Says:

    You should not pass your secret(!!!) to the approval url!
    And you can add a redirect url. If you capture that url (on your webserver) you’ll know that the user is ready. No redirect will occur if the user does not approve….

    see..:
    https://www.dropbox.com/developers/reference/api#authorize

  9. Psycho Says:

    Visual Studio gives me an error at the line:
    signature = HttpUtility.UrlEncode(signature);
    > The name HttpUtility doesn’t exist in the current context.

    What should I do?

    • Christophe Says:

      Make sure you have added a reference to the System.Web assembly and check the .NET profile you are targetting.

      Probably set to the Client Profile right now, which does not offer the System.Web assembly.

      Set it to the full profile. Just right click on your project in the solution explorer and select project properties.

    • Psycho Says:

      Figured it out. Thanks anyways.

      One more question; how do I get it to work in .Net Framework 2?

      • Christophe Says:

        Phew, I’d have to figure that out myself. Don’t know off the top of my head. Target the .NET 2 framework, compile and see what breaks. Then you have to refactor those parts. Don’t know which non .NET 2 parts I exactly used in all of the 6 articles. The JSON serialization supports .NET 2, so that’s already good news:

        http://james.newtonking.com/projects/json-net.aspx

        The rest you’ll have to figure out yourself. Can’t imagine it ‘ll be much.

  10. aziodale Says:

    hi,
    I program in vb.net and I’m trying to translate the code, are in phase Request token and after the line
    Dim response = request.GetResponse ()

    the result is failure of the remote server: (401) Unauthorized.

    I checked the signature and it is like the example
    and the content of request seems like:

    https://api.dropbox.com/1/oauth/request_token?oauth_consumer_key=your api key&oauth_nonce=9328214&oauth_timestamp=1325081302&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=OskIFg2iOhcVJ2qHGDN6VDXxUik%3d

    What can I do?
    Where i can find vb sample code?

    regards

  11. vince Says:

    ahm, just wanted to ask if var signature = oAuth.GenerateSignature(new Uri(uri), consumerKey, consumerSecret,
    oauthToken.Token, oauthToken.Secret, “GET”, timeStamp, nonce,
    OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters); the oauthToken.Token and oauthToken.Secret, where did it came from?

  12. Devi Says:

    Hi,
    I am getting an error in Process.start(authorizeurl), when the code is deployed on the server. Could please help on this?

    Regards,
    A.Devi

  13. Muhammad Salman Says:

    Thanks you so much, Great :)

  14. Anders Frey Says:

    Very neat walkthrough. Great for getting started with the Dropbox API.

  15. sakthi eswar Says:

    Hi whenever i access the dropbox using javascript the alert window (allow or deny) asking me every time i want it only one time that is very first time when i access the dropbox anyone tell me what should i do for that.

    • André Saraiva Says:

      Hello sakthi, when you authenticate the first time, you get an access token. You should save it, so that you can use it on the next time. Doing this, you wont need to Allow the app every time.

  16. sakthieswar Says:

    Hi,
    how to store that access_token and reuse it. Using that access_token how to upload (writefile) file to dropbox please send me.

    I get the access_token from client.oauth.token how i ll save it and reuse it

  17. sakthieswar Says:

    Hi am getting token = “wtqnwruqh74gjqz”
    i want to upload a file to dropbox using below function
    client.writeFile(“hello_world.txt”, “Hello, world!\n”, function (error, stat) {}. without clicking allow in the grant me page pls help how to do this one.

  18. André Saraiva Says:

    Hi,
    are you using an third party SDK for JS or the REST api?
    If you’re using REST, you’ll need to send the access token in the http authorization header with some other info.

    Something like this:

    OAuth
    oauth_token=”{token}”,
    oauth_consumer_key=”{consumerKey}”,
    oauth_signature_method=”PLAINTEXT”,
    oauth_signature=”{signature}”,
    oauth_version=”1.0″

  19. sakthi eswar Says:

    Hi i got access_token and i can upload the file to dropbox through
    client.writefile(); this was working in mozila and chrome only but in IE i got an javascript runtime error :

    Error is: Microsoft JScript runtime error: Access is denied.

    what should i do for work this code in IE please help me.

  20. HiralBhimani Says:

    signature = HttpUtility.UrlEncode(signature);

    Error of “HttpUtility” Does not exist in current Context
    how to solve it ?

  21. Jeff Law Says:

    I’m a VB.Net developer. I have converted all of the C# code to VB, but am getting a weird syntax error on …

    Protected Class QueryParameterComparer
    Implements IComparer(Of QueryParameter)

    Public Function Compare(x As QueryParameter, y As QueryParameter) As Integer
    If x.Name = y.Name Then
    Return [String].CompareOrdinal(x.Value, y.Value)
    End If

    Return [String].CompareOrdinal(x.Name, y.Name)
    End Function
    End Class

    The error is “Class ‘QueryParameterComparer’ must implement ‘Function Compare(x As DropBoxVB.OAuthProtocol.OAuthBase.QueryParameter, y As DropBoxVB.OAuthProtocol.OAuthBase.QueryParameter) As Integer’ for interface ‘System.Collections.Generic.IComparer(Of QueryParameter)’”

    Any ideas as to the reason??

    • André Saraiva Says:

      It seems that you’ve forgot to write the sentence: “implements icomparer(of queryparameter).compare” at the end of the line you declared the function, after “as integer”

      • Jeff Law Says:

        I tried that, but got a similar error!
        I now have …
        Public Function Compare(ByVal x As QueryParameter, ByVal y As QueryParameter) As Integer
        … and it works


  22. […] is some great information on integrating your app with dropbox using .NET. http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/ […]

  23. Anuradha Says:

    I get an error at this line, of the GetAccessToken:

    var response = request.GetResponse();

    The remote server returned an error: (401) Unauthorized

  24. Anuradha Says:

    I have created an app using ‘create an app’ link.
    I am trying to run your application but getting error.
    Please help me out why my call is marked as unauthorized every time. My url issuing the request is
    https://api.dropbox.com/1/oauth/access_token?oauth_consumer_key=l16pc18jqktqbuk&oauth_nonce=9182052&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1373538701&oauth_token=WvfoP83EC4jUjMIQ&oauth_version=1.0&oauth_signature=WP07qMe3hzuFgTKv/2Tx3eYWGME=

    which redirects to this url:
    https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token%3DWvfoP83EC4jUjMIQ&signup_tag=oauth&signup_data=387208

    and application generates error “The remote server returned an error: (401) Unauthorized”

    • André Saraiva Says:

      It may be a proxy authentication issue. Do you have a proxy Server in your network? If so, you must set its configurarion on the request, before calling request.getresponse()

  25. Evelyn Loo Says:

    Does dropbox sdk for IOS support proxy setting?I have set up the proxy setting in the Settings app and seems that dropbox sdk doesn’t add the proxy setting at the http request. Is it I need to set in anyway in the code?

  26. wlloo Says:

    Does dropbox sdk rest service support proxy setting?
    I am using dropbox sdk DBRestClient method – (void)loadMetadata:(NSString*)path; in my own ios application,
    I have set up the proxy setting in the Settings app and seems that dropbox sdk doesn’t add the proxy setting on the http request. Is it I need to set in anyway in the code?

  27. Pradeep Kesharwani Says:

    Does this REST API is used for Windows phone to access list of files within a folder


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 335 other followers

%d bloggers like this: