Thursday, June 30, 2011

WP7 WebBrowser caching and Facebook login/logout

So you want to developed your next social media integrated Windows Phone application;
And you’re making heavy use of Facebook C# SDK.

But you’ll find out that all the authentication/authorization/delegation process is done entirely in a WebBrowser component and developer is just intercepting Navigated event of this component to process the server responses and capture the Access Tokens.

It comes a bit more trickier when you try to log-out in order to log-in with another credentials.
Not so much info over the internet, so here it was my solution that works just fine:

- when we wish to log-out we pass to the browser log-out URL:

wb.Navigate(new Uri("http://m.facebook.com/logout.php?confirm=1"));

- then on the navigated event of WebBrowser component we look for logout button, extract the logout Url and we force a navigation to this real logout Url:

private void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
string fbLogoutDoc = wb.SaveToString();
Regex regex = new Regex("\\<A href=\\\"(.*)\\\".*data-sigil=\\\"logout\\\"");
MatchCollection matches = regex.Matches(fbLogoutDoc);
if (matches.Count > 0)
{
string finalLogout = string.Format("http://m.facebook.com{0}", matches[0].Groups[1].ToString());
wb.Navigate(new Uri(finalLogout));
}
}

This way the browser will not cache Facebook login cookies and next time when we intent to authenticate a new user/credentials the login screen will appear nicely. And of course, if we logout the user from a different screen as the login one, the webbrowser component can be made “invisible”


Just my simple solution for a clean windows phone facebook logout.

2 comments:

  1. Nice solution but I use "wb_LoadCompleted" instate "wb_Navigated"
    because my internet is low speed it have effect to "fbLogoutDoc" can not collect all data.

    And I change

    string finalLogout = string.Format("http://m.facebook.com{0}", matches[0].Groups[1].ToString());

    to

    string finalLogout = string.Format("http://m.facebook.com{0}", matches[0].Groups[1].ToString().Replace("amp;", ""));

    bacause it have "amp;" in expected URL it have effect to logout incomplete.

    //-----

    Hope this help another one have problem me :)

    ReplyDelete
  2. Hi Chong,

    Thank you for this finding,
    In our case it wasn't a problem because we use an "invisible" web browser to logout, but for other cases your finding is more suitable and might apply.

    Regards,
    Claudiu Farcas

    ReplyDelete