コード例 #1
0
        private async Task <Uri> GetLoginUrl(string permissions)
        {
            var parameters = new Dictionary <string, object>();

            String appId = await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId");

            parameters["client_id"]     = appId;
            parameters["redirect_uri"]  = "https://www.facebook.com/connect/login_success.html";
            parameters["response_type"] = "token";
#if WP8 || WINDOWS_PHONE
            parameters["display"] = "touch";
            parameters["mobile"]  = true;
#else
            parameters["display"] = "popup";
#endif

            // add the 'scope' only if we have extendedPermissions.
            if (!string.IsNullOrEmpty(permissions))
            {
                // A comma-delimited list of permissions
                parameters["scope"] = permissions;
            }

            var client = new FacebookClient();
            return(client.GetLoginUrl(parameters));
        }
コード例 #2
0
        internal void LoginWithApp(string permissions, string state)
        {
            var task = Task.Run(async() => await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId"));

            task.Wait();
            AppAuthenticationHelper.AuthenticateWithApp(task.Result, permissions, state);
        }
コード例 #3
0
        public override Uri MapUri(Uri uri)
        {
            var tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString());

            try
            {
                AccessTokenData session = new AccessTokenData();
                session.ParseQueryString(HttpUtility.UrlDecode(uri.ToString()));
                if (!String.IsNullOrEmpty(session.AccessToken))
                {
                    var task = Task.Run(async() => await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId"));
                    task.Wait();



                    session.AppId = task.Result;
                    Session.ActiveSession.CurrentAccessTokenData = session;

                    // trigger the event handler with the session
                    if (Session.OnFacebookAuthenticationFinished != null)
                    {
                        Session.OnFacebookAuthenticationFinished(session);
                    }

                    if (Session.OnSessionStateChanged != null)
                    {
                        Session.OnSessionStateChanged(LoginStatus.LoggedIn);
                    }
                }
            }
            catch (Facebook.FacebookOAuthException exc)
            {
            }

            if (uri.ToString().StartsWith("/Protocol"))
            {
                // Read which page to redirect to when redirecting from the Facebook authentication.
                var RedirectPageNameTask =
                    Task.Run(async() => await AppAuthenticationHelper.GetFacebookConfigValue("RedirectPage", "Name"));
                RedirectPageNameTask.Wait();
                Session.ActiveSession.RedirectPageOnSuccess = String.IsNullOrEmpty(RedirectPageNameTask.Result)
                    ? "MainPage.xaml"
                    : RedirectPageNameTask.Result;

                return(new Uri("/" + Session.ActiveSession.RedirectPageOnSuccess, UriKind.Relative));
            }
            else
            {
                var RedirectPageNameTask =
                    Task.Run(async() => await AppAuthenticationHelper.GetFilteredManifestAppAttributeValue("DefaultTask", "NavigationPage", String.Empty));
                RedirectPageNameTask.Wait();

                return(new Uri("/" + RedirectPageNameTask.Result, UriKind.Relative));
            }
        }
コード例 #4
0
        public static void FacebookAuthenticationReceived(ProtocolActivatedEventArgs protocolArgs)
        {
            if (protocolArgs == null)
            {
                throw new ArgumentNullException("protocolArgs");
            }

            // If this invocation is because of a dialog dismissal, dismiss the dialog
            // TODO: (sanjeevd) Fire the event handler when the dialog is done - via the browser
            if (OnDialogDismissed != null)
            {
                OnDialogDismissed(protocolArgs.Uri);
            }


            // parse and fill out the token data
            try
            {
                AccessTokenData tokenData = new AccessTokenData();
                tokenData.ParseQueryString(Facebook.HttpHelper.UrlDecode(protocolArgs.Uri.ToString()));
                if (!String.IsNullOrEmpty(tokenData.AccessToken))
                {
                    var task = Task.Run(async() => await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId"));
                    task.Wait();
                    tokenData.AppId = task.Result;
                    Session.ActiveSession.CurrentAccessTokenData = tokenData;

                    // trigger the event handler with the session
                    if (Session.OnFacebookAuthenticationFinished != null)
                    {
                        Session.OnFacebookAuthenticationFinished(tokenData);
                    }

                    if (Session.OnSessionStateChanged != null)
                    {
                        Session.OnSessionStateChanged(LoginStatus.LoggedIn);
                    }
                }
            }
            catch (Facebook.FacebookOAuthException exc)
            {
                // TODO: (sanjeevd) catch appropriately
            }
        }
コード例 #5
0
 public void LoginWithApp(string permissions, string state)
 {
     AppAuthenticationHelper.AuthenticateWithApp(this.AppId, permissions, state);
 }
コード例 #6
0
 async public Task LoginWithApp(string permissions, string state)
 {
     await AppAuthenticationHelper.AuthenticateWithApp(this.AppId, permissions, state);
 }
コード例 #7
0
        /// <summary>
        /// TODO: Extend an SSO token daily. This should be an internal method
        /// </summary>
        /// <returns></returns>
        public async static Task CheckAndExtendTokenIfNeeded()
        {
            // get the existing token
            if (String.IsNullOrEmpty(ActiveSession.CurrentAccessTokenData.AccessToken))
            {
                // If there is no token, do nothing
                return;
            }

            // check if its issue date is over 24 hours and if so, renew it
            if (DateTime.UtcNow - ActiveSession.CurrentAccessTokenData.Issued > TimeSpan.FromHours(24)) // one day
            {
                var    client         = new HttpClient();
                String tokenExtendUri = "https://graph.facebook.com/v2.1";
                client.BaseAddress = new Uri(tokenExtendUri);

                var request = new HttpRequestMessage();

                var mfdc   = new MultipartFormDataContent();
                var _appId = await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId");

                mfdc.Add(new StringContent(_appId), name: "batch_app_id");

                String extensionString = "[{\"method\":\"GET\",\"relative_url\":\"oauth\\/access_token?grant_type=fb_extend_sso_token&access_token=" + ActiveSession.CurrentAccessTokenData.AccessToken + "\"}]";
                mfdc.Add(new StringContent(extensionString), name: "batch");

                HttpResponseMessage response = await client.PostAsync(tokenExtendUri, mfdc);

                String resultContent = await response.Content.ReadAsStringAsync();

                var result = SimpleJson.DeserializeObject(resultContent);

                // extract the access token and save it in the session
                var data = (List <object>)result;

                var dictionary = (IDictionary <string, object>)data[0];
                var code       = (long)dictionary["code"];
                if (code == 200)
                {
                    // the API succeeded
                    var body         = (IDictionary <string, object>)SimpleJson.DeserializeObject((string)dictionary["body"]);
                    var access_token = (string)body["access_token"];
                    var expires_at   = (long)body["expires_at"];

                    var accessTokenData = new AccessTokenData();
                    // token extension failed...
                    accessTokenData.AccessToken = access_token;

                    // parse out other types
                    long expiresInValue;
                    var  now = DateTime.UtcNow;
                    accessTokenData.Expires = now + TimeSpan.FromSeconds(expires_at);
                    accessTokenData.Issued  = now - (TimeSpan.FromDays(60) - TimeSpan.FromSeconds(expires_at));
                    accessTokenData.AppId   = _appId;

                    // Assign the accessTokenData object over, this saves it to the disk as well.
                    ActiveSession.CurrentAccessTokenData = accessTokenData;
                }
                else
                {
                    // return an error?? Since this is token extension, maybe we should wait until the token is finally expired before throwing an error.
                }
            }
        }
コード例 #8
0
        async public void LoginWithBehavior(string permissions, FacebookLoginBehavior behavior)
        {
            switch (behavior)
            {
            case FacebookLoginBehavior.LoginBehaviorMobileInternetExplorerOnly:
            {
#if (WP8 || WINDOWS_PHONE)
                String appId = await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId");

                Uri uri =
                    new Uri(
                        String.Format(
                            "https://m.facebook.com/v2.1/dialog/oauth?redirect_uri={0}%3A%2F%2Fauthorize&display=touch&state=%7B%220is_active_session%22%3A1%2C%22is_open_session%22%3A1%2C%22com.facebook.sdk_client_state%22%3A1%2C%223_method%22%3A%22browser_auth%22%7D&scope={2}&type=user_agent&client_id={1}&sdk=ios",
                            String.Format("fb{0}", appId), appId, permissions), UriKind.Absolute);

                Launcher.LaunchUriAsync(uri);
                break;
#else
                throw new NotImplementedException("Internet explorer based login is not available on Windows");
#endif
            }

            case FacebookLoginBehavior.LoginBehaviorWebViewOnly:
            {
                String appId = await AppAuthenticationHelper.GetFacebookConfigValue("Facebook", "AppId");

#if WP8 || WINDOWS_PHONE
                Uri uri =
                    new Uri(
                        String.Format(
                            "https://m.facebook.com/v2.1/dialog/oauth?redirect_uri={0}%3A%2F%2Fauthorize&display=touch&state=%7B%220is_active_session%22%3A1%2C%22is_open_session%22%3A1%2C%22com.facebook.sdk_client_state%22%3A1%2C%223_method%22%3A%22browser_auth%22%7D&scope={2}&type=user_agent&client_id={1}&sdk=ios",
                            String.Format("fb{0}", appId), appId, permissions), UriKind.Absolute);
#else
                Uri uri = await GetLoginUrl(permissions);
#endif
                WebviewAuthentication.AuthenticateAsync(WebAuthenticationOptions.None, uri, null);
                break;
            }

            case FacebookLoginBehavior.LoginBehaviorWebAuthenticationBroker:
#if WINDOWS
            {
                try
                {
                    // TODO: What to do here? LoginAsync returns inproc. Login with IE returns out of proc?
                    var result = await LoginAsync(permissions, FacebookLoginBehavior.LoginBehaviorWebAuthenticationBroker);

                    // when the results are available, launch the event handler
                    if (OnFacebookAuthenticationFinished != null)
                    {
                        OnFacebookAuthenticationFinished(result);
                    }

                    if (OnSessionStateChanged != null)
                    {
                        OnSessionStateChanged(LoginStatus.LoggedIn);
                    }
                }
                catch (FacebookOAuthException e)
                {
                    if (OnSessionStateChanged != null)
                    {
                        OnSessionStateChanged(LoginStatus.LoggedOut);
                    }
                }

                break;
            }
#else
                {
                    throw new NotImplementedException("WebviewAuthentication is not implemented on Windows Phone");
                }
#endif// WINDOWS

            case FacebookLoginBehavior.LoginBehaviorApplicationOnly:
            {
#if WP8 || WINDOWS_PHONE
                LoginWithApp(permissions);
                break;
#else
                throw new NotImplementedException("Login via app is not available on Windows");
#endif
            }
            }
        }
コード例 #9
0
 /// <summary>
 /// Authenticates via app to app communication with the Facebook app
 /// </summary>
 /// <param name="appId">The application id for which the user needs to be authenticated.</param>
 /// <param name="permissions">List of permissions that are being requested.</param>
 /// <param name="state">The state, this will be passed back in the response</param>
 internal static async void AuthenticateWithApp(string appId, string permissions, string state)
 {
     var    redirectUri = AppAuthenticationHelper.GetFacebookLoginCallbackSchemeName() + "://authorize";
     string uriString   = string.Format(AppAuthenticationHelper.FacebookConnectUriTemplate, appId, permissions, redirectUri, HttpUtility.UrlEncode(state == null ? string.Empty : state));
     await Launcher.LaunchUriAsync(new Uri(uriString));
 }
コード例 #10
0
 internal void LoginWithApp(string permissions, string state)
 {
     AppAuthenticationHelper.AuthenticateWithApp(Session.AppId, permissions, state);
 }
コード例 #11
0
        public Uri MapUri(Uri uri)
#endif
        {
            var             tempUri = uri.ToString();
            FacebookUriType uriType = FacebookUriType.Login;

#if WP8
            if (tempUri.StartsWith(string.Format("/Protocol?encodedLaunchUri={0}", Session.LoginRedirectUri)))
            {
                uriType = FacebookUriType.Login;
            }
            else if (tempUri.StartsWith(string.Format("/Protocol?encodedLaunchUri={0}", Session.AppRequestRedirectUri)))
            {
                uriType = FacebookUriType.AppRequest;
            }
            else if (tempUri.StartsWith(string.Format("/Protocol?encodedLaunchUri={0}", Session.FeedRedirectUri)))
            {
                uriType = FacebookUriType.Feed;
            }
#else
            if (tempUri.StartsWith(WebUtility.UrlDecode(Session.LoginRedirectUri)))
            {
                uriType = FacebookUriType.Login;
            }
            else if (tempUri.StartsWith(WebUtility.UrlDecode(Session.AppRequestRedirectUri)))
            {
                uriType = FacebookUriType.AppRequest;
            }
            else if (tempUri.StartsWith(WebUtility.UrlDecode(Session.FeedRedirectUri)))
            {
                uriType = FacebookUriType.Feed;
            }
#endif

            if (uriType == FacebookUriType.Login)
            {
                try
                {
                    AccessTokenData session = new AccessTokenData();
                    session.ParseQueryString(WebUtility.UrlDecode(uri.ToString()));
                    if (!String.IsNullOrEmpty(session.AccessToken))
                    {
                        session.AppId = Session.AppId;
                        Session.ActiveSession.CurrentAccessTokenData = session;

                        // trigger the event handler with the session
                        if (Session.OnFacebookAuthenticationFinished != null)
                        {
                            Session.OnFacebookAuthenticationFinished(session);
                        }

                        if (Session.OnSessionStateChanged != null)
                        {
                            Session.OnSessionStateChanged(LoginStatus.LoggedIn);
                        }
                    }
                }
                catch (Facebook.FacebookOAuthException exc)
                {
                    // fire the authentication finished handler with the exception
                    if (Session.OnFacebookAuthenticationFinished != null)
                    {
                        Session.OnFacebookAuthenticationFinished(null);
                    }
                }
            }
            else if (uriType == FacebookUriType.AppRequest)
            {
                // parsing query string to get request id and facebook ids of the people the request has been sent to
                // or error code and error messages
                FBResult fbResult = new FBResult();

                try
                {
                    fbResult.Json = new JsonObject();

#if WP8
                    string queryString = GetQueryStringFromUri(HttpUtility.UrlDecode(tempUri));
#else
                    string queryString = GetQueryStringFromUri("/Protocol?encodedLaunchUri=" + WebUtility.UrlDecode(tempUri));
#endif

                    string[] queries = queryString.Split('&');
                    if (queries.Length > 0)
                    {
                        string        request = string.Empty;
                        List <string> toList  = new List <string>();

                        foreach (string query in queries)
                        {
                            string[] keyValue = query.Split('=');
                            if (keyValue.Length >= 2)
                            {
                                if (keyValue[0].Contains("request"))
                                {
                                    request = keyValue[1];
                                }
                                else if (keyValue[0].Contains("to"))
                                {
                                    toList.Add(keyValue[1]);
                                }
                                else if (keyValue[0].Contains("error_code"))
                                {
                                    fbResult.Error = keyValue[1];
                                }
                                else if (keyValue[0].Contains("error_message"))
                                {
                                    fbResult.Text = keyValue[1].Replace('+', ' ');
                                }
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(request))
                        {
                            fbResult.Json.Add(new KeyValuePair <string, object>("request", request));
                            fbResult.Json.Add(new KeyValuePair <string, object>("to", toList));
                        }

                        // If there's no error, assign the success text
                        if (string.IsNullOrWhiteSpace(fbResult.Text))
                        {
                            fbResult.Text = "Success";
                        }
                    }
                }
                catch
                {
                    fbResult.Error = "Failure";
                    fbResult.Text  = "AppRequest cancelled or ended with exceptional state";
                }

                // trigger the event handler with the session
                if (Session.OnFacebookAppRequestFinished != null)
                {
                    Session.OnFacebookAppRequestFinished(fbResult);
                }
            }
            else if (uriType == FacebookUriType.Feed)
            {
                // parsing query string to get request id and facebook ids of the people the request has been sent to
                // or error code and error messages
                FBResult fbResult = new FBResult();

                try
                {
                    // parsing query string to get request id and facebook ids of the people the request has been sent to
                    // or error code and error messages
                    fbResult.Json = new JsonObject();

#if WP8
                    string queryString = GetQueryStringFromUri(HttpUtility.UrlDecode(tempUri));
#else
                    string queryString = GetQueryStringFromUri("/Protocol?encodedLaunchUri=" + WebUtility.UrlDecode(tempUri));
#endif

                    string[] queries = queryString.Split('&');
                    if (queries.Length > 0)
                    {
                        string        postId = string.Empty;
                        List <string> toList = new List <string>();

                        foreach (string query in queries)
                        {
                            string[] keyValue = query.Split('=');
                            if (keyValue.Length >= 2)
                            {
                                if (keyValue[0].Contains("post_id"))
                                {
                                    postId = keyValue[1];
                                }
                                else if (keyValue[0].Contains("error_code"))
                                {
                                    fbResult.Error = keyValue[1];
                                }
                                else if (keyValue[0].Contains("error_msg"))
                                {
                                    fbResult.Text = keyValue[1].Replace('+', ' ');
                                }
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(postId))
                        {
                            fbResult.Json.Add(new KeyValuePair <string, object>("post_id", postId));
                        }
                    }

                    // If there's no error, assign the success text
                    if (string.IsNullOrWhiteSpace(fbResult.Text))
                    {
                        fbResult.Text = "Success";
                    }
                }
                catch
                {
                    fbResult.Error = "Failure";
                    fbResult.Text  = "Feed cancelled or ended with exceptional state";
                }

                // trigger the event handler with the session
                if (Session.OnFacebookFeedFinished != null)
                {
                    Session.OnFacebookFeedFinished(fbResult);
                }
            }

            if (uri.ToString().StartsWith("/Protocol"))
            {
                // Read which page to redirect to when redirecting from the Facebook authentication.
                var RedirectPageNameTask =
                    Task.Run(async() => await AppAuthenticationHelper.GetFacebookConfigValue("RedirectPage", "Name"));
                RedirectPageNameTask.Wait();
                Session.ActiveSession.RedirectPageOnSuccess = String.IsNullOrEmpty(RedirectPageNameTask.Result)
                    ? "MainPage.xaml"
                    : RedirectPageNameTask.Result;

                return(new Uri("/" + Session.ActiveSession.RedirectPageOnSuccess, UriKind.Relative));
            }

            // Otherwise perform normal launch.
            return(uri);
        }