Introduction
This application very easily integrates Tumblr with your application without wanting you to go deep into the OAuth complexities. OAuth is used to manage authorization & authentication. Thus, there's no need for the application to save or even know the user's Tumblr login credentials. Hence it is safe from user's perspective as well.
Background
Targeted for beginners who have no idea about how OAuth works, or C# syntax of making requests to Tumblr API. I started the same way and even after digging hard on the internet, could not find a working solution in C# that integrates Tumblr using OAuth.
Using the Code
This project does the following:
- Authenticates user on Tumblr
- Authorizes from user
- Creates a new post on the blog (After reading this tip, you would be able to do a lot more than just this.)
Follow instructions on Tumblr API documentation and register your application. The registration process is very easy. Let your application URL be where your website runs. Let us keep the localhost URL (Run your website to find this in your browser address bar. Example.: http://localhost:51432/SiteName/) for now. Enter something in redirect URL. I'll let you know what to enter there later. After saving the settings, you should see your app on
Download the code attached with this tip and add Helper.cs class file into your website. This class holds all the methods that we require. You need not go into much detail.
Next, add page Tumblr.aspx into your website from the code source.
Add to page a button (ID=btnAuthorize
, Text="Authenticate & Authorize"
), a timer, a scriptManager
for the timer and a hidden field. Put in the following code:
Helper requestHelper = new Helper();
protected void Page_Load(object sender, EventArgs e)
{
Helper.TumblrConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
Helper.TumblrConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
requestHelper.CallBackUrl = "http://localhost:51288/Pages/IntermediatePage.aspx";
if (!IsPostBack)
{
hdnField.Value = requestHelper.GetAuthorizationLink();
}
}
Add the following script to Tumblr.aspx to open the Tumblr login page as a popup.
<script type="text/javascript">
function OpenTumblrWindow() {
var txt = document.getElementById('hdnField');
var urlstring = txt.value;
window.open(urlstring, '_blank', 'height=500,width=800,status=yes,
toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no');
}
</script>
Call this on button click.
<asp:Button runat="server"
Text="Authorize" ID="btnAuthorize"
OnClientClick="OpenTumblrWindow();"
OnClick="btnAuthorize_Click" />
protected void btnAuthorize_Click(object sender, EventArgs e)
{
timer.Enabled = true; //Start the timer
}
Now add to code Intermediate.cs public static class
:
public static class Intermediate
{
public static string TumblrVerifier = string.Empty;
public static bool IsResponseReceived = false;
}
Now add IntermediatePage.aspx into your website and add the following script:
<script type="text/javascript">
function CloseSelf() {
self.close();
}
</script>
In its code behind:
protected void Page_Load(object sender, EventArgs e)
{
Intermediate.TumblrVerifier = Request.QueryString["oauth_verifier"];
Intermediate.IsResponseReceived = true;
ScriptManager.RegisterClientScriptBlock(this, typeof(string),
"CloseSelf", "CloseSelf();", true);
}
Now, on your Tumblr website, login, go to URL http://www.tumblr.com/oauth/apps and into the redirect URL, type in the address for this page. Example: http://localhost:51432/SiteName/IntermediatePage.aspx .
Set requestHelper.CallBackUrl
in your page load event for Tumblr.aspx to this value as well.
Now, run your website, the following sequence of actions occur.
- Tumblr.aspx page load sets appropriate value for hidden field. Here, behind the scenes, using your client secret & client token, we make a request to receive request tokens and authorize the application using user intervention.
- Click on 'Authenticate & Authorize' to open popup window. If you are not signed in, Login to Tumblr using your credentials. The application asks you to grant access. click on 'Allow'. Tumblr now redirects you to your redirect URL, in our case http://localhost:51432/SiteName/IntermediatePage.aspx
- TumblrVerifier in Intermediate gets set. We have the verifier code with us now. JavaScript closes the popup window.
Now, we need to make Tumblr.aspx know that we are having the code with us now. Add button (ID="btnPost", Text="Post Blog"
and a label (ID="lblSuccess")
). Please write the below code for its timer tick event.
Clicking on btnAuthorize
enables the timer & it keeps checking if the code is received in Intermediate.TumblrVerifier
. In case of any error, verifier won't be received. So we set IsResponseReceived
to deal with this case which indicates that some response has been received; disable the timer.
protected void timer_Tick1(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Intermediate.TumblrVerifier))
{
btnPost.Visible = true;
lblSuccess.Visible = true;
timer.Enabled = false;
lblSuccess.Text = "Authentication Successful..";
}
else if (Intermediate.IsResponseReceived)
{
lblSuccess.Text = "User denied access";
lblSuccess.Visible = true;
timer.Enabled = false;
Intermediate.IsResponseReceived = false;
}
}
Now, for posting blog, add 2 textboxes, one for blog title and the other for blog content. in the btnPost
click event:
protected void btnPost_Click(object sender, EventArgs e)
{
try
{
string AccessTokenResponse = requestHelper.GetAccessToken
(Helper.TumblrToken, Intermediate.TumblrVerifier);
string[] tokens = AccessTokenResponse.Split('&');
string accessToken = tokens[0].Split('=')[1];
string accessTokenSecret = tokens[1].Split('=')[1];
KeyValuePair<string, string> LoginDetails = new KeyValuePair
<string, string>(accessToken, accessTokenSecret);
var url2 = "http://api.tumblr.com/v2/user/dashboard";
string BLOGURL = Helper.OAuthData(url2, "GET",
LoginDetails.Key, LoginDetails.Value, null);
BLOGURL = BLOGURL.Substring(BLOGURL.IndexOf("post_url") + 10,
BLOGURL.IndexOf("slug") - BLOGURL.IndexOf("post_url") - 10);
BLOGURL = BLOGURL.Replace("http:", "").
Replace("\"", "").Replace("/", "").
Replace("\\", "").Trim();
BLOGURL = BLOGURL.Substring(0, BLOGURL.IndexOf(".com") + 4);
var prms = new Dictionary<string, object>();
prms.Add("type", "text");
prms.Add("title", txtBlogTitle.Text);
prms.Add("body", txtBlogContent.Text);
var postUrl2 = "http://api.tumblr.com/v2/blog/" +
BLOGURL + "/post";
string result = Helper.OAuthData(postUrl2, "POST",
LoginDetails.Key, LoginDetails.Value, prms);
lblSuccess.Text = result;
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse && ex.Response != null)
{
StreamReader exReader = new StreamReader(ex.Response.GetResponseStream());
lblSuccess.Text = exReader.ReadToEnd();
}
}
}
This is it! After making your website live, you can change the application URL and callback URL into Tumblr app settings accordingly.
For using other functionality that suits your need, you just have to use relevant URLs of tumblr API.
Points of Interest
It was quite annoying as I was not able to make OAuth work even after days of work put in. It was a pure trial and error process which I got stuck in getting access token and thereafter in making suitable requests to the API. The mistake I was making was in passing appropriate authentication header with the request. Got it working finally.
References
History
- 16th April, 2013: Initial version