The day before yesterday, we looked at an sample with Twitter: we retrieved the tweets from the public timeline in an OOB trusted application. The public timeline feed on Twitter requires no credentials to be passed along. Some other feeds however do, such as the user timeline (containing your own tweets) and the friends timeline (containing the tweets of your friends).
Up until Silverlight 4, passing credentials to a service was not supported. Silverlight 3 added support for the ClientHttp stack, however, it was not possible to modify the authorization header, resulting in it being impossible to pass credentials. Silverlight 4 adds this support however. In combination with the support for cross-domain access for services for Silverlight if they are executed with elevated permissions, we can easily build a more complete Twitter client in Silverlight. We already did some work on this application, we will now extend it to make it possible to execute requests to services that require authorization.
Below is a screenshot of the modified application, running OOB as a trusted application.
We will not be looking at the code for the public timeline, that was already covered two days ago. Instead, let’s focus on the code we need to write to make the authorized request possible. Of course, we need the user’s credentials, therefore, I added a username/password field.
When clicking on the Submit button, two request are being executed:
Here’s the code for the first one. Note a few things. Passing credentials is only possible if using the ClientHttp stack. This is enabled by WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp). This selects the ClientHttp stack instead of the browser http stack, which is used by default. To pass the credentials, we use the Credentials property and set it to an instance of NetworkCredentials. Here’s the code.
//try finding the user tweets and friends tweets
string userTimeLine = "http://twitter.com/statuses/user_timeline/" +
UserNameTextBox.Text + ".xml";
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(UserNameTextBox.Text,
client.UseDefaultCredentials = false;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler
client.DownloadStringAsync(new Uri(userTimeLine, UriKind.Absolute));
A very important line is setting the UseDefaultCredentials to false. If we set it to true, Silverlight will pass the credentials of the logged-on user on the machine (NTLM). If this is the wanted behavior however, simply setting this property to true will of course enable this.
The complete code for this application can be downloaded here:SLTwitterCredentials.zip (82.89 KB)