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:

public class TwitterSettings  
    {
        public static string ConsumerKey = YOUR CONSUMER KEY";
        public static string ConsumerKeySecret = "YOUR CONSUMER SECRET"; 
        public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
        public static string OAuthVersion = "1.0";
        public static string CallbackUri = "YOUR CALLBACK URI";
        public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
        public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";
    }

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

public class TwitterAccess  
    {
        public string AccessToken { get; set; }
        public string AccessTokenSecret { get; set; }
        public string UserId { get; set; }
        public string ScreenName { get; set; }
    }

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

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">  
    <TextBlock x:Name="ApplicationTitle" Text="PHOTO LIGHT" Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="authorize twitter" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <TextBlock Text="Log in and copy the PIN here:" Style="{StaticResource PhoneTextLargeStyle}"></TextBlock>
    <StackPanel Orientation="Horizontal">
        <TextBox Name="pinText" Width="240" Margin="0,12,12,12" BorderThickness="1" BorderBrush="Black"/>
        <Button Content="Confirm" Click="Button_Click" Margin="0,12,0,12"/>
    </StackPanel>
    <phone:WebBrowser Name="BrowserControl" Height="480"/>
</StackPanel>

In the code behind, define the following:

private OAuthRequestToken _requestToken;  
private TwitterService service;

public AccountPage()  
{
    InitializeComponent();
}

On navigating to the page, get Twitter token:

protected override void OnNavigatedTo(NavigationEventArgs e)  
{
    GetTwitterToken();
}

private void GetTwitterToken()  
{
    service = new TwitterService(TwitterSettings.ConsumerKey, TwitterSettings.ConsumerKeySecret);
    var cb = new Action<OAuthRequestToken,TwitterResponse>(CallBackToken);
    service.GetRequestToken("oob", CallBackToken);
}

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.

void CallBackToken(OAuthRequestToken rt, TwitterResponse response)  
        {
            Uri uri = service.GetAuthorizationUri(rt);
            _requestToken = rt;
            BrowserControl.Dispatcher.BeginInvoke(() => BrowserControl.Navigate(uri));
        }

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:

private void Button_Click(object sender, RoutedEventArgs e)  
        {
            if (String.IsNullOrEmpty(pinText.Text))
                MessageBox.Show("Please enter PIN");
            else
            {
                try
                {
                    var cb = new Action<OAuthAccessToken, TwitterResponse>(CallBackVerifiedResponse);
                    service.GetAccessToken(_requestToken, pinText.Text, CallBackVerifiedResponse);
                }
                catch
                {
                    MessageBox.Show("Something is wrong with the PIN. Try again please.", "Error", MessageBoxButton.OK);
                }
            }
        }

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.

void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)  
        {
            if (at != null)
            {
                SerializeHelper.SaveSetting<TwitterAccess>("TwitterAccess", new TwitterAccess
                    {
                        AccessToken = at.Token,
                        AccessTokenSecret = at.TokenSecret,
                        ScreenName = at.ScreenName,
                        UserId = at.UserId.ToString()
                    });
            }
    }

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

 

comments powered by Disqus