Dropbox REST API Part 1: Authentication
December 29, 2011
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…
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”
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.
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).
Keep those tokens nearby. You’ll need them when signing in to Dropbox.
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:
- Request token: Obtain an OAuth request token to be used for the rest of the authentication process.
- Authorize: The user must grant your application access to their Dropbox.
- 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.
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.
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:
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.
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.
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.
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.











January 4, 2012 at 8:59u
good
January 7, 2012 at 19:14u
Awesome!! Thank you!!
January 29, 2012 at 1:12u
I get an error at this line, of the GetAccessToken:
var response = request.GetResponse();
403. Forbidden.
January 29, 2012 at 1:49u
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?
January 30, 2012 at 17:13u
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
January 30, 2012 at 17:20u
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.
February 16, 2012 at 22:02u
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
February 16, 2012 at 22:37u
If you could mail me your code I’ll have a look this weekend.
February 16, 2012 at 22:46u
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?
February 16, 2012 at 22:52u
geersch@gmail.com ….. could be that you leave too little time between step 2 and 3 …
February 16, 2012 at 22:56u
No, i put a Console.ReadLine(); in order to press a key when the Allow process is finished…
February 16, 2012 at 23:01u
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!
February 16, 2012 at 23:06u
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.”}
February 16, 2012 at 23:09u
Thx. Glad it helped.
February 27, 2012 at 4:24u
You should use PLAINTEXT signature method, makes things much easier.
April 16, 2012 at 8:14u
This worked so well with Windows 8 metro too, with few changes to oauthBase.cs. Great article!
August 18, 2012 at 17:49u
Can you please provide the changes you’ve made to port it to Metro apps?
March 10, 2013 at 15:54u
@srinivas can you share code.
March 10, 2013 at 15:56u
@srinivas can u share code
April 18, 2012 at 12:22u
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
April 18, 2012 at 13:00u
Smee, thx for the comment. Indeed for step #2 only the oauth token is required. I’ll modify the article later.
As far the callback / redirect, I explained that here:
http://cgeers.com/2012/03/17/dropbox-rest-api-part-6-oauth-callback.
April 20, 2012 at 20:46u
Corrected the error. Regards.
May 13, 2012 at 21:15u
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?
May 13, 2012 at 21:18u
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.
May 13, 2012 at 21:20u
Figured it out. Thanks anyways.
One more question; how do I get it to work in .Net Framework 2?
May 13, 2012 at 21:27u
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.
June 6, 2012 at 17:21u
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
August 8, 2012 at 1:39u
Have you figured out why is this happening? I have the same issue here…
January 11, 2013 at 9:53u
The solution is to change the Signature.Types, both GetRequestToken () as in GetAccessToken (). To make things easier I send you the code I’m using:
http://pastebin.com/Gt0PYjts
I hope that you still need this information.
And thanks to Christopher for the tutorial, this best!
Greetings from Cartagena – Colombia
PS: Sorry for my English …
September 28, 2012 at 8:22u
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?
September 29, 2012 at 13:20u
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
October 22, 2012 at 0:56u
Thanks you so much, Great
December 15, 2012 at 14:18u
Very neat walkthrough. Great for getting started with the Dropbox API.
February 4, 2013 at 15:14u
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.
February 4, 2013 at 22:41u
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.
February 5, 2013 at 8:57u
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
February 5, 2013 at 11:06u
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.
February 5, 2013 at 22:21u
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″
February 7, 2013 at 12:16u
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.
March 22, 2013 at 22:36u
signature = HttpUtility.UrlEncode(signature);
Error of “HttpUtility” Does not exist in current Context
how to solve it ?