Authorizing on WPF (.NET 4.5) or Windows Phone 8

Mobile and desktop applications cannot usually handle the callback step of the OAuth flow, where the server calls back to an app-specified URL with parameters required to obtain the access token. These kind of apps are good candidates to use xAuth instead, which is a variant of the OAuth flow that does not involve a callback URL and uses the user's password to sign the request.

Warning: xAuth is disabled by default by Tumblr and you will need to request it to be enabled before you can use it. There is a handy link in your Tumblr application page for this, and it usually takes Tumblr 1 - 2 days to follow through.

Enough talk for now, let's see how to do xAuth using Tumblr#! You will need to add a reference to:
  • DontPanic.TumblrSharp.dll
  • DontPanic.TumblrSharp.Client.dll (not necessary, but you will probably use it later)
  • DontPanic.TumblrSharp.Net45.dll (or DontPanic.TumblrSharp.WP8.dll if you are building for Windows Phone 8)
Doing xAuth is as simple as the following code:

namespace Sample.Net45
{
    using DontPanic.TumblrSharp;
    using DontPanic.TumblrSharp.OAuth;
    using System.Threading.Tasks;

    public class TestXAuth
    {
        public async Task<Token> DoXAuthAsync(string userName, string password)
        {
            string consumerKey = "<your consumer key here>";
            string consumerSecret = "<your consumer secret here>";

            //instantiate the OAuth client factory
            var factory = new OAuthClientFactory();

            //create the OAuthClient
            var oauthClient = factory.Create(consumerKey, consumerSecret);
            try
            {
                //perform the xAuth asynchronously; pass the user name and 
                //the password here and receive the access token
                var token = await oauthClient.PerformXAuthAsync(userName, password);
                if (token.IsValid)
                {
                    //we've got the token. Tumblr access tokens do not expire, 
                    //so it is a good idea to store it somewhere permanently so 
                    //that it can be used from now on
                    return token;
                }
                else
                {
                    //should not happen
                    return null;
                }
            }
            catch (OAuthException ex)
            {
                //an error occurred while performing xAuth
                return null;
            }
        }
    }
}


NOTE: xAuth requires the user to supply his user name and password only to be able to sign the authorization request: once the access token has been received there is no need for the user's password anymore. PLEASE DO NOT STORE THE USER PASSWORD IN YOUR APP!!



Last edited Aug 26, 2013 at 2:52 AM by turboronin, version 7