:::: MENU ::::

Twitter authentication from Windows Phone app

Just like with Facebook, sharing statuses on Twitter from Windows Phone app can be simply accomplished using ShareStatusTask launcher. A more complicated scenario is when you want to share a photo on Twitter. In order to do that, you first need to authenticate the user from your app to allow your app to communicate with Twitter and then to upload photos. This article will show you how to do the authentication part.

Before doing the authentication, you need to make sure you register your app on:

https://dev.twitter.com/apps

Login with your Twitter account. Create a new application if you haven’t already done so.

image

After that, you’ll get Consumer Key and Consumer Secret keys that you’ll use from your Windows Phone app. Next, go to your Windows Phone app or create a new one. Create a class called TwitterSettings.cs with the following static properties:

Hardcode your consumer key, consumer secret and the callback URI (you defined that when registering your app on dev.twitter.com).

The next step is to add a library called TweetSharp to your project. In my opinion, that’s the best open source library for communicating with Twitter from C#.

https://github.com/danielcrenna/tweetsharp

The fastest way to get it is through Nuget.

Now create a Windows Phone page for authentication. Let’s take a look at how does the process of authentication go. You will use something called a PIN-based authentication.

https://dev.twitter.com/docs/auth/pin-based-authorization

This means that you’ll have to ask the user to login with his Twitter account using Browser control (or WebBrowser launcher) after which he’ll get a PIN. The user will then copy that PIN somewhere inside your app after which you’ll get information you need to do stuff on user’s Twitter. This information includes Access Token, Access Token Secret, UserID and Screen Name. You should create a class for holding that information (something similar to what I showed you in in my Facebook authentication article). Call it TwitterAccess.cs

Now, define the rest of the page for authentication, something like this:

In the code behind, define the following:

On navigating to the page, get Twitter token:

You create the TwitterService object with the ConsumerKey and ConsumerKeySecret, the hardcoded values from TwitterSettings class. Then you define the callback method which you’ll use for getting the authentication URI and navigate the browser to it. Then you call the GetRequestToken method with parameters “oob” and that callback method to get the request token. Parameter “oob” means that we are using the PIN-based authentication method. The callback method gets the necesssary authentication URI and then opens that URI in the browser control.

The browser will display a Twitter website login with your app info, telling the user that your app wants access to their account. If they login, they’ll get back a PIN. After they copy that PIN to your textbox and press the login button, then you do the following:

The most important part is defining the callback method for getting the access token, CallBackVerifiedResponse, and call the GetAccessToken method with parameters: request token that you got earlier, the PIN that the user copy/pasted to your textbox and the name of the callback method. The CallBackVerifiedResponse method checks to see if the token was actually acquired (if the PIN was entered correctly or not) and then serializes information to isolated storage.

If you don’t know how to write the serialization method SaveSetting, see here in one of my last articles regarding the Facebook authentication:

http://igrali.com/2012/06/05/facebook-authentication-from-windows-phone-app/

That’s all you need to do. Now you have the access token and access token secret which you’ll use for anything you need to do with Twitter from your app!

If you want to see how it’s done in an app, go check my app Photo Light!

twittFirst

twittSecond

 

Share the knowledge

32 Comments

  • Reply Steve Williams (Konaju Games) |

    Interesting that you chose PIN-based, especially since it is designed for applications that cannot embed a web browser. You should use the oauth_callback and extract the access token from the URI. Better user experience in that the user does not have to manually copy and paste anything.

  • Reply gorbi |

    Should the “navigated” or the “loaded” parameter of the browser element link to the OnNavigatedTo method? I’m confused about the order in which the methods are called (and where it actually starts)

    • Reply igrali |

      No, as you can see in the XAML code, the browser doesn’t have any events attached to it.

      So, there’s a page constructor and OnNavigatedTo method as entrance, and from there you should be able to follow which method calls which…

      • Reply gorbi |

        I didn’t know or notice that OnNavigatedTo was an overridden method, thanks. One more question: I’m trying to copy the SerializeHelper class that you’re also using in your FB tutorial but I’m getting an error with the DataContractSerializer class. VS says it can’t find it and I tried ‘using’ several namespaces but can’t seem to fix it. Any idea what the problem could be? Here’s the code: pastie.org/private/esdljykshgarspg98jop6g

        • Reply igrali |

          Have you added System.Runtime.Serialization to your references inside your project?

          What exactly does VS say?

          Here’s what I have used in the class, and it works:

          using System;
          using System.IO;
          using System.IO.IsolatedStorage;
          using System.Runtime.Serialization;
          using System.Windows;

      • Reply gorbi |

        Yea I had all of those. I had to add System.Runtime.Serialization.dll to my project references to get it to work. Thanks for your help!

  • Reply Kanadaj |

    I’ve followed this one, it works great (the best so far), but I just can’t seem to be able to upload images with this… Could you help me? :)

    • Reply igrali |

      Thanks!

      This is just for authentication. I will write an article about uploading images to Twitter probably tonight or tomorrow.

      • Reply kanadaj |

        Oh wow this was an extremely fast reply :)
        My problem is that using the following code the client does nothing at all, and I just doN’t know what the problem is as I don’t even get an exception:
        image is a WriteAbleBitmap. I’m sorry to just put it in here like this, but I have to finish this one soon and my time is quite… Limitied ^^

        RestClient restClient = new RestClient
        {
        Authority = “https://upload.twitter.com”,
        HasElevatedPermissions = true,
        Credentials = credentials,
        Method = WebMethod.Post
        };

        RestRequest restRequest = new RestRequest
        {
        Path = “1/statuses/update_with_media.json”,
        };

        MemoryStream stream = new MemoryStream();
        image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, 10);

        restRequest.AddParameter(“status”, message);
        restRequest.AddFile(“media[]“, “TI.jpg”, stream, “image/jpg”);
        restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

        • Reply igrali |

          Where does it break? What is the problem and where?
          Is this all the code for uploading that you have?

          Try setting the stream position to 0 after calling SaveJpeg, that was giving me quite some trouble…

      • Reply kanadaj |

        Oh god, thank you :D It did not upload because it couldnt process the stream but didnt give an exception nor did it break ^^

  • Reply chefdog |

    As mentioned earlier, why would you use pin based authentication? Is there any advantadge? I mean if simple login in the browser also works, why would you make things more complex for a user? Unless pin based authentication is safer? of?

    • Reply igrali |

      Hi, thanks for your comment.

      I’d say that the advantage of PIN based authentication is that it’s elegant and easy to implement for you as a developer. Disadvantage is that it takes a step more from a user to authenticate.

      Using browser login and parameter parsing is more complex to implement, but makes it easier for the user to authenticate.

      I don’t think there’s any security implication. The method described in this blog post is the one I used in one of my apps and I simply decided to share it with others. The reader/dev has to decide what’s best for him, his app and his users. :)

      • Reply kanadaj |

        private void OAuthWebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
        string html = OAuthWebBrowser.SaveToString();
        if (html.Contains(“"))
        {
        int i = html.IndexOf("
        ") + 6;
        string code = html.Substring(i, 7);

        try
        {
        var cb = new Action(CallBackVerifiedResponse);
        service.GetAccessToken(_requestToken, code, CallBackVerifiedResponse);
        }
        catch
        {
        MessageBox.Show("Something is wrong with the PIN. Try again please.", "Error", MessageBoxButton.OK);
        }
        }
        }

        Using this code, you can make the PIN authentication just as easy as normal authentication is for the user, but you don't have to make a normal authentication ^^

      • Reply kanadaj |

        Oh, it removed the keyword from IndexOf() and Contains(), the string is

  • Reply yashu |

    my VS Says “The name ‘SerializeHelper’ does not exist in the current context”..what might be the problem..i added reference to system.Runtime.Serialization…

  • Reply Shilpa |

    Hi, good post, but am facing a problem here. THe code just works fine in the emulatore but while running the code in device i get a null exception in void
    void CallBackToken(OAuthRequestToken rt, TwitterResponse response)
    {
    Uri uri = service.GetAuthorizationUri(rt);
    _requestToken = rt;
    BrowserControl.Dispatcher.BeginInvoke(() => BrowserControl.Navigate(uri));
    }
    The method is called in GetTwitterToken().and the parameter rt is coming as null while running in device.Pls help me out here

  • Reply Shilpa |

    I found out the problem. The device date and time was not correct. So it was giving request token null exception. So everyone make sure that the phone date time is correct.

  • Reply Dee |

    hello,

    nice post i know it kinda of old but can you please help? i getting a

    unauthorizedAccessException in the serializeHelper class at the

    messageBox.show(e.Message); at the end of the code not sure why

    thanks in advnace

So, what do you think ?