Decided to write this post because it took me some time to find the answer. Maybe you already know that if you use OAuth Facebook connect inside your Windows Phone application there is one step where you use the WebBrowser control to let the user authenticate on the Facebook server and authorize your app. The "problem" presents itself when you want to link another user because the WebBrowser control has already memorized the old credentials and will automatically use them. What needs to be done is to logout the old user from the WebBrowser without actually telling the user to go on the web page and click logout. I have found 3 easy ways to do that: the first two will work on both Windows Phone 7.x and Windows Phone 8 and are Facebook specific and the third one will only work on Windows Phone 8 (generic method for OAuth providers). The 3 methods can use the WebBrowser control headless (you don't actually have to show the WebBrowser control to the user and don't even have to have the webbrowser attached to a Page):
Method 1: described by Rene Schulte in this blog post
The method constructs the logout Uri using your AppId and a SessionKey that is obtained from the AccessToken you got when the user authenticated.
Get the SessionKey:
private static string ExtractSessionKeyFromAccessToken(string accessToken)
{
if (!String.IsNullOrEmpty(accessToken))
{
var parts = accessToken.Split('|');
if (parts.Length > 2)
{
return parts[1];
}
}
return String.Empty;
}
Obtain the logout 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);
}
Make the WebBrowser navigate to the logout Uri:
Browser.Navigate(FacebookService.GetLogoutUri(EndpointData.Settings.Facebook));
Method 2:
If for some reason you don't have the Facebook AppId available (my case) you can use the WebBrowser to navigate to the Logout page https://www.facebook.com/logout.php and after the page gets loaded you just execute the script document.forms['logout_form']:
wb.LoadCompleted += wb_LoadCompleted;
wb.Navigate(new Uri("https://www.facebook.com/logout.php"));
Once the page gets loaded: void wb_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
wb.LoadCompleted -= wb_LoadCompleted;
if (wb.SaveToString().Contains("logout_form"))
wb.InvokeScript("eval", "document.forms['logout_form'].submit();");
}
Method 3:
This is the easiest one, but will only work on Windows Phone 8: call the new WebBrowser async method ClearCookiesAsync(). This method works for every OAuth provider (Dropbox, Box, Skydrive, Picasa, Flickr, Google Drive... infinite list).
NAMASTE
0 comments:
Post a Comment