简体   繁体   中英

Facebook logout Windows Phone Application without opening WebBrowser

I am trying to develop a Windows Phone 7 application using Facebook login and logout operations. I found Facebook SDK and used it in order to carry out login, by opening WebBrowser. The user enters credentials to this browser and logs in successfully. Moreover, I managed to login the user without using any SDK, just using http requests, like the SDK actually does. However, I want to logout users without using any WebBrowser, but just clicking a button for example. There are so many solutions in the web suggesting that I should open web browser and navigate it to a certain URL in order to logout. However, this is not what I want. I think there should be a way to logout by clearing cookies, which I dont exactly know how to do, or any other that you suggest. Some part of my code below:

    private static String appID = "";
    private static String appSecret = "";

    public static void login(String[] permissions)
    {
        try
        {
            permissionArray = permissions;

            popup = new Popup();
            popup.Height = 480;
            popup.Width = 480;
            popup.VerticalOffset = 100;
            FacebookLoginUserControl control = new FacebookLoginUserControl();
            control.facebookWebBrowser.Loaded += new RoutedEventHandler(webBrowser_Loaded);
            control.facebookWebBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser_Navigated);

            popup.Child = control;
            popup.IsOpen = true;
        }
        catch (Exception e)
        {
            //handle
        }
    }

    private static void webBrowser_Loaded(Object sender, RoutedEventArgs e)
    {
        WebBrowser wb = (WebBrowser)sender;
        String loginUrl = GetFacebookLoginUrl();
        wb.Navigate(new Uri(loginUrl));
    }

    private static String GetFacebookLoginUrl()
    {
        String permissionString = String.Empty;
        if (permissionArray.Length > 0)
            permissionString = String.Join(",", permissionArray);

        var uriParams = new Dictionary<string, string>() {
                    {"client_id", appID},
                    {"response_type", "token"},
                    {"scope", permissionString},
                    {"redirect_uri", "http://www.facebook.com/connect/login_success.html"},
                    {"display", "touch"}
                };
        StringBuilder urlBuilder = new StringBuilder();
        foreach (var current in uriParams)
        {
            if (urlBuilder.Length > 0)
            {
                urlBuilder.Append("&");
            }
            var encoded = HttpUtility.UrlEncode(current.Value);
            urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
        }
        var loginUrl = "http://www.facebook.com/dialog/oauth?" + urlBuilder.ToString();

        return loginUrl;
    }

    private static void webBrowser_Navigated(Object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        if (string.IsNullOrEmpty(e.Uri.Fragment)) return;
        if (e.Uri.AbsoluteUri.Replace(e.Uri.Fragment, "") == "http://www.facebook.com/connect/login_success.html")
        {
            string text = HttpUtility.HtmlDecode(e.Uri.Fragment).TrimStart('#');
            var pairs = text.Split('&');
            foreach (var pair in pairs)
            {
                var kvp = pair.Split('=');
                if (kvp.Length == 2)
                {
                    if (kvp[0] == "access_token")
                    {
                        accessToken = kvp[1];
                        MessageBox.Show("Access granted");
                        RequestUserProfile();
                    }
                }
            }
            if (string.IsNullOrEmpty(accessToken))
            {
                MessageBox.Show("Unable to authenticate");
            }
            popup.IsOpen = false;
        }
    }

    private static void RequestUserProfile()
    {
        var profileUrl = string.Format("https://graph.facebook.com/me?access_token={0}", HttpUtility.UrlEncode(accessToken));
        request = (HttpWebRequest)HttpWebRequest.Create(new Uri(profileUrl));
        request.Method = "GET";
        request.BeginGetResponse(result =>
        {
            try
            {
                var resp = (result.AsyncState as HttpWebRequest).EndGetResponse(result);
                using (var strm = resp.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(strm);
                    var responseString = sr.ReadToEnd();

                }
            }
            catch (Exception ex)
            {
                //
            }
        }, request);
    }

Any Ideas to solve the problem. Thanks in advance

What's actually so spooky in using webBrowser? If you programmatically create a WebBrowser object, it won't be visible, unless you'd add it somewhere on form/page. If you want to clear cookies for Facebook, the solution will be something like that:

// Can be invoked from your button_click event
 public void TryLogout()
        {
            webBrowser = new WebBrowser();

            Uri uri = new Uri("http://m.facebook.com/home.php?r", UriKind.Absolute);
            webBrowser.LoadCompleted += new LoadCompletedEventHandler(webBrowser_TryLogoutLoadCompleted);
            webBrowser.Navigate(uri);
        } 

And then:

private void webBrowser_TryLogoutLoadCompleted(object sender, EventArgs e)
        {
            try
            {
                var cookies = webBrowser.GetCookies();

                foreach (Cookie cookie in cookies)
                {
                    if (cookie.Domain.Contains("m.facebook.com"))
                    {
                        cookie.Discard = true;
                        cookie.Expired = true;
                    }
                }
            // we've just cleaned up cookies

            }
            finally
            {
                webBrowser.LoadCompleted -= webBrowser_TryLogoutLoadCompleted;
            }
        }

Hope this helps.

GetCookies method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM