,

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




Introduction





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


   


Behind The Scene






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...


Publisher: Tapan kumar - 6:15 AM