Thursday, January 5, 2012

Let me out - Facebook Logout in a Windows Phone App

A while ago I implemented the Facebook photo endpoint into my Windows Phone Pictures Lab app. The implementation of the login was quite straightforward thanks to OAuth 2.0. Only the logout was way harder than one might expect. This post describes how to logout from Facebook using the Facebook API.






In my Pictures Lab app you can edit photos, make them look awesome and then save or share those with your friends at Twitter or Facebook. The Windows Phone Mango API provides the ShareLinkTask and the ShareStatusTask which can be used by an app to share an URL or text using the social services the user has connected the device to. Unfortunately there's no built-in SharePhotoTask to share a photo using the services the user has already authorized. That's why I had to implement it in a custom way where the user has to authorize again. This blog post by my mate Nick Randolph describes very well how to login to Facebook from a Windows Phone app.

For some situations it might make sense to allow the user to logout from within the app. One might think this can't be hard and in most cases it's pretty easy. Logging out from Twitter is very easy for example. You just have to start the authorization process again. However, logging out from Facebook is way harder since they store a cookie and the WebBrowser control doesn't provide a way to clear the cookies, so just starting the authorization process again doesn't work.
One way to log out from Facebook uses a special Uri that contains a part of the access token which was queried during the app authorization process.

Here's the snippet I use in Pictures Lab to split the access token to get the session key which is then used to build the custom Uri:


public Uri GetLogoutUri(FacebookCredentials credentials)
{
   var sessionkey = ExtractSessionKeyFromAccessToken(credentials.AccessToken);
   var url = String.Format("http://facebook.com/logout.php?app_key={0}&session_key={1}&next={2}", EndpointData.FacebookAppId, sessionkey, EndpointData.FacebookLogoutCallbackUrl);
   return new Uri(url);
}

private static string ExtractSessionKeyFromAccessToken(string accessToken)
{
   if (!String.IsNullOrEmpty(accessToken))
   {
      var parts = accessToken.Split('|');
      if (parts.Length > 2)
      { 
         return parts[1];
      }
   }
   return String.Empty;
}

That logout Uri is then used to navigate the WebBrowser control to it which then correctly triggers the log out process.

Browser.Navigate(FacebookService.GetLogoutUri(EndpointData.Settings.Facebook));

That's it. You just have to know their trick. Hope this helps.

17 comments:

  1. Ok, so that's how you do it. I had given up. Thanks for sharing Rene.

    Cheers,
    Daniel

    ReplyDelete
  2. Thanks a lot for shearing this apps. Now got how this log out process works.

    ReplyDelete
  3. Have you covered how to post an image generated in your app to Facebook or Twitter?

    I want to Share an image directly from the MediaLibrary, but it looks like I would have to post it to some 3rd party server first (twitpic or Flickr). This would require the user to log into that service first.

    Alternatively, I could have some Azure storage, but the cost may be prohibitive.

    What do you suggest?

    ReplyDelete
  4. I use the Hammock and TweetSharp libraries for Twitter, which is pretty straightforward. You will also probably find some posts out there.
    For FB I use custom code. The Graph API is pretty good documented.

    ReplyDelete
  5. Hi. My access token does not contain the session key, just the access token itself (I've got no | to split it from). What can I do to make it appear?

    Thanks!

    ReplyDelete
  6. Hmm, that's strange. Are you sure you requested the access token during the auth process (see the response_type param)?

    ReplyDelete
  7. Yes, I get back a response in the style of

    http://my.site.com/facebook_connect.html#access_token=AAAC...DZD&expires_in=5559

    I can use the access token to perform actions via the Graph API, so there is no problem. The logout however does not work if I put the access token there.

    Thanks!

    ReplyDelete
  8. Problem solved!

    There is an alternate logout URL that can be passed the access token (from: http://developers.facebook.com/docs/authentication/)

    https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN

    It seems to work OK.

    ReplyDelete
  9. Hi, Rene. You said: "Logging out from Twitter is very easy for example. You just have to start the authorization process again."
    But it does not work for me.
    When I do authorization process again browser opens page "Twitter Authorize application" with only buttons "Authorize app" and "No, thanks" (so user remains logged in), but not the previous page where I can enter username and password. Can you give more detail information how to log out from Twitter?

    Thanks.

    ReplyDelete
  10. You should find a log out option on the Twitter auth page that is loaded.
    If not, just close your app and start over again. It's just session related and only appears if you logged in right before trying log out. A normal user workflow won't be log in and immediately log out, so it won't happen like 99% of the time. Makes sense?

    ReplyDelete
  11. Thanks for quick reply. I checked and it is actually works when I close app and start it over again. Your article is very useful!

    Thanks.

    ReplyDelete
  12. I have applied the code. but it didn't work. Cookies count is zero. Can you post whole code for log-out event.

    ReplyDelete
  13. Thanks. I solved the problem below code,
    webBrowser.Navigate(new Uri(String.Format("https://www.facebook.com/logout.php?next={0}&access_token={1}", getLoginUrl(), AccessToken)));

    ReplyDelete
  14. I just got my Lumia 920 yesterday and just discovered how to logout of the Facebook app. In the upper left hand corner of the running Facebook app is an icon that looks like 3 horizontal lines. Tap that and you get a menu of all the things you can normally control from Facebook online (like privacy, preferences and stuff). If you scroll all the way to the bottom of that menu, you'll find the logout.

    ReplyDelete
  15. I have to say that my patience with Windows Phone is wearing off. There are two reasons for this. The first is the lack of real progress on the application front. The second is the feeling of abandonment surrounding the Nokia Lumia 900 or more broadly, Microsoft’s inability to even get a minor update like Windows Phone 7.8 fully rolled out. Facebook Connect App Development at Cygnis

    ReplyDelete
  16. Can you please clarify what "app_key" means? Is this the Application ID, Application Secret Key or Application Access Token. Thank you and best regards.

    ReplyDelete
  17. app_key is the Id you get from FB when you register an app.

    ReplyDelete