// this whole showdialog below is to avoid the race condition where one message dialog is being killed // but the second one comes up before the first one is gone and the framework throws an "UnauthorizedAccessException" // solution from: http://stackoverflow.com/questions/13813065/winrt-messagedialog-showasync-will-throw-unauthorizedaccessexception-in-my-cus Task ShowDialog(AccessTokenData session) { CoreDispatcher dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher; Func<object, Task<bool>> action = null; action = async (o) => { try { if (dispatcher.HasThreadAccess) await new MessageDialog("Authentication via Webview succeeded. Expiry date: " + session.Expires.ToString()).ShowAsync(); else { dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action(o)); } return true; } catch (UnauthorizedAccessException) { if (action != null) { Task.Delay(500).ContinueWith(async t => await action(o)); } } return false; }; return action(null); }
private async void OnFacebookAuthenticationFinished(AccessTokenData session) { // here the authentication succeeded callback will be received. // put your login logic here try { FacebookClient client = new FacebookClient(session.AccessToken); //Graph request and result dynamic result = await client.GetTaskAsync("me"); //Getting current user from graph request result var currentUser = new Facebook.Client.GraphUser(result); //Do something with current user data var fad = new FacebookAccountData() { SocialNetworkId = currentUser.Id, Name = currentUser.Name, LastName = currentUser.LastName, FirstName = currentUser.FirstName, Email = "", Link = currentUser.Link, MiddleName = currentUser.MiddleName }; } catch (Exception ex) { //Handle exception } }
private async System.Threading.Tasks.Task RetriveUserInfo(AccessTokenData accessToken) { var client = new Facebook.FacebookClient(accessToken.AccessToken); dynamic result = null; bool failed = false; try { result = await client.GetTaskAsync("me?fields=id,birthday,first_name,last_name,middle_name,gender"); } catch(Exception e) { failed = true; } if(failed) { MessageDialog dialog = new MessageDialog("Facebook is not responding to our authentication request. Sorry."); await dialog.ShowAsync(); throw new Exception("Windows phone does not provide an exit function, so we have to crash the app."); } string fullName = string.Join(" ", new[] { result.first_name, result.middle_name, result.last_name }); string preferredName = result.last_name; bool? gender = null; if (result.gender == "female") { gender = true; } else if (result.gender == "male") { gender = false; } DateTime birthdate = DateTime.UtcNow - TimeSpan.FromDays(365 * 30); if (result.birthday != null) { birthdate = DateTime.Parse(result.birthday); } var currentUser = new Facebook.Client.GraphUser(result); long facebookId = long.Parse(result.id); UserState.ActiveAccount = await Api.Do.AccountFacebook(facebookId); if (UserState.ActiveAccount == null) { Frame.Navigate(typeof(CreatePage), new CreatePage.AutofillInfo { SocialId = facebookId, Authenticator = Authenticator.Facebook, Birthdate = birthdate, FullName = fullName, Gender = gender, PreferredName = preferredName }); } else { Frame.Navigate(typeof(MainPage), UserState.CurrentId); } }
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)); } }
public override void SaveSessionData(AccessTokenData data) { lock (_fileLock) { var serializer = new XmlSerializer(typeof(AccessTokenData)); var store = IsolatedStorageFile.GetUserStoreForApplication(); using (var stream = store.OpenFile(fileName, FileMode.Create)) { serializer.Serialize(stream, data); } } }
public override void SaveSessionData(AccessTokenData data) { var settings = ApplicationData.Current.LocalSettings; var composite = new ApplicationDataCompositeValue(); composite["AccessToken"] = data.AccessToken; composite["AppId"] = data.AppId; composite["CurrentPermissions"] = string.Join(",", data.CurrentPermissions); composite["Expires"] = data.Expires.ToString(); composite["Issued"] = data.Issued.ToString(); composite["FacebookId"] = data.FacebookId; settings.Values[key] = composite; }
public override void SaveSessionData(AccessTokenData data) { lock (_fileLock) { var serializer = new XmlSerializer(typeof(AccessTokenData)); var store = IsolatedStorageFile.GetUserStoreForApplication(); using (var stream = store.OpenFile(fileName, FileMode.Create)) { serializer.Serialize(stream, data); } } }
public override void SaveSessionData(AccessTokenData data) { var settings = ApplicationData.Current.LocalSettings; var composite = new ApplicationDataCompositeValue(); composite["AccessToken"] = data.AccessToken; composite["AppId"] = data.AppId; composite["CurrentPermissions"] = string.Join(",", data.CurrentPermissions); composite["Expires"] = data.Expires.ToString(); composite["Issued"] = data.Issued.ToString(); composite["FacebookId"] = data.FacebookId; settings.Values[key] = composite; }
/// <summary> /// Initializes a new instance of the AccessTokenData class from a query string with key/value pairs /// </summary> /// <param name="queryString"> /// Query to parse /// </param> public static void ParseQueryString(this AccessTokenData session, string queryString) { if (string.IsNullOrWhiteSpace(queryString)) { throw new InvalidDataException(); } // parse out errors, if any var error = GetQueryStringValueFromUri(queryString, ErrorKey); var errorDescription = GetQueryStringValueFromUri(queryString, ErrorDescriptionKey); var errorReason = GetQueryStringValueFromUri(queryString, ErrorReasonKey); int errorCodeValue = 0; int.TryParse(GetQueryStringValueFromUri(queryString, ErrorCodeKey), out errorCodeValue); if (string.IsNullOrEmpty(error) && errorCodeValue == 0) { // parse out string values session.AccessToken = GetQueryStringValueFromUri(queryString, AccessTokenKey); session.State = GetQueryStringValueFromUri(queryString, StateKey); //var encodedLaunchUri = GetQueryStringValueFromUri(queryString, EncodedLaunchUri); //if (!String.IsNullOrEmpty(encodedLaunchUri)) //{ // //session.AppId = encodedLaunchUri.Substring(2); // ignore the fb // var index = encodedLaunchUri.IndexOf(":", StringComparison.InvariantCulture); // var appId = encodedLaunchUri.Substring(2, index - 2); // if (!String.IsNullOrEmpty(appId)) // { // } //} // parse out other types long expiresInValue; DateTime now = DateTime.UtcNow; if (long.TryParse(GetQueryStringValueFromUri(queryString, ExpiresInKey), out expiresInValue)) { session.Expires = now + TimeSpan.FromSeconds(expiresInValue); session.Issued = now - (TimeSpan.FromDays(MaxTokenLifeTime) - TimeSpan.FromSeconds(expiresInValue)); } } else { throw new FacebookOAuthException( string.Format("{0}: {1}", error, errorDescription), errorReason, errorCodeValue, 0); } }
// TODO: Should we handle the data changing? //public FacebookSessionLocalSettingsCacheProvider() //{ // Windows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged; //} //void Current_DataChanged(ApplicationData sender, object args) //{ //} //public event Windows.Foundation.TypedEventHandler<FacebookSession, object> SessionChanged; // NOTE: This provider must handle changes in the app data over different versions of a Store App. // If we update the SDK and the data format changes, we should automatically migrate to prevent // app crashes and poor user experience (i.e. forced to login after app updates). public override AccessTokenData GetSessionData() { var settings = ApplicationData.Current.LocalSettings; var composite = (ApplicationDataCompositeValue)settings.Values[key]; if (composite == null) { return(null); } var session = new AccessTokenData { AccessToken = (string)composite["AccessToken"], FacebookId = (string)composite["FacebookId"], AppId = (string)composite["AppId"] }; var expires = (string)composite["Expires"]; if (!string.IsNullOrEmpty(expires)) { DateTime date; if (DateTime.TryParse(expires, out date)) { session.Expires = date; } } var issued = (string)composite["Issued"]; if (!string.IsNullOrEmpty(issued)) { DateTime date; if (DateTime.TryParse(issued, out date)) { session.Issued = date; } } var perms = (string)composite["CurrentPermissions"]; if (!string.IsNullOrEmpty(perms)) { var p = perms.Split(','); session.CurrentPermissions.AddRange(p); } return(session); }
private async void OnFacebookAuthenticationFinished(AccessTokenData fbSession) { IsLoading = true; var sessionResponse = await QuickbloxClient.AuthenticationClient.CreateSessionWithSocialNetworkKey("facebook", "public_profile", fbSession.AccessToken, null, null); if (sessionResponse.StatusCode == HttpStatusCode.Created) { NavigationService.Navigate(ViewLocator.Dialogs, new DialogsNavigationParameter { CurrentUserId = sessionResponse.Result.Session.UserId, Password = sessionResponse.Result.Session.Token }); } IsLoading = false; }
// TODO: Should we handle the data changing? //public FacebookSessionLocalSettingsCacheProvider() //{ // Windows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged; //} //void Current_DataChanged(ApplicationData sender, object args) //{ //} //public event Windows.Foundation.TypedEventHandler<FacebookSession, object> SessionChanged; // NOTE: This provider must handle changes in the app data over different versions of a Store App. // If we update the SDK and the data format changes, we should automatically migrate to prevent // app crashes and poor user experience (i.e. forced to login after app updates). public override AccessTokenData GetSessionData() { var settings = ApplicationData.Current.LocalSettings; var composite = (ApplicationDataCompositeValue)settings.Values[key]; if (composite == null) { return null; } var session = new AccessTokenData { AccessToken = (string)composite["AccessToken"], FacebookId = (string)composite["FacebookId"], AppId = (string)composite["AppId"] }; var expires = (string)composite["Expires"]; if (!string.IsNullOrEmpty(expires)) { DateTime date; if (DateTime.TryParse(expires, out date)) { session.Expires = date; } } var issued = (string)composite["Issued"]; if (!string.IsNullOrEmpty(issued)) { DateTime date; if (DateTime.TryParse(issued, out date)) { session.Issued = date; } } var perms = (string)composite["CurrentPermissions"]; if (!string.IsNullOrEmpty(perms)) { var p = perms.Split(','); session.CurrentPermissions.AddRange(p); } return session; }
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 } }
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)) { tokenData.AppId = Session.AppId; 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 } }
/// <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. } } }
// ReSharper restore InconsistentNaming, UnusedMember.Global #region Private methods /// <summary> /// Updates an AccessTokenData object with data fetched from FB API. /// Updates ActiveSession with updated AccessTokenData object. /// Uses CurrentAccessTokenData if parameter is null /// </summary> /// <param name="tempToken">AccessTokenData object to update</param> /// <returns>LoginStatus object</returns> private static Task<LoginStatus> UpdateAndGetLoginStatus(AccessTokenData tempToken = null) { var tcs = new TaskCompletionSource<LoginStatus>(); Deployment.Current.Dispatcher.BeginInvoke(async () => { if (tempToken != null) CurrentTokenData = tempToken; if (string.IsNullOrEmpty(CurrentTokenData.AccessToken)) { tcs.SetResult(new LoginStatus { Status = "unknown" }); return; } await Session.CheckAndExtendTokenIfNeeded(); if (CurrentTokenData.CurrentPermissions.Count == 0 || string.IsNullOrEmpty(CurrentTokenData.FacebookId)) { // Create a copy of existing access token data to update it with new values var newTokenData = CurrentTokenData.Clone(); try { var result = (JsonObject) await FbClient.GetTaskAsync("debug_token", new { input_token = CurrentTokenData.AccessToken }); var data = (JsonObject)result.ToDictionary(pair => pair.Key, pair => pair.Value)["data"]; var userId = (string)data.ToDictionary(pair => pair.Key, pair => pair.Value)["user_id"]; newTokenData.FacebookId = userId; var actualPermissions = (JsonArray)data.ToDictionary(pair => pair.Key, pair => pair.Value)["scopes"]; foreach (var actualPermission in actualPermissions) { newTokenData.CurrentPermissions.Add((string)actualPermission); } Session.ActiveSession.CurrentAccessTokenData = newTokenData; } catch { // No need to fail here, just return a loginStatus object without userID } } var loginStatus = new LoginStatus { Status = "connected", AuthResponse = new AuthResponse { AccessToken = CurrentTokenData.AccessToken, ExpiresIn = CurrentTokenData.Expires, UserId = CurrentTokenData.FacebookId } }; tcs.SetResult(loginStatus); }); return tcs.Task; }
/// <summary> /// Fetches data returned by login dialog from callback uri. Creates and saves new AccessTokenData object to current session. /// Calls getLoginStatus internally to fill AccessTokenData with such values as FacebookId and CurrentPermissions /// </summary> /// <param name="uri">Callback uri of login dialog</param> private static Task<AccessTokenData> FetchLoginUriAsync(Uri uri) { var tcs = new TaskCompletionSource<AccessTokenData>(); Deployment.Current.Dispatcher.BeginInvoke(() => { var oauthResult = FbClient.ParseOAuthCallbackUrl(uri); if (oauthResult.IsSuccess) { var tempToken = new AccessTokenData { AccessToken = oauthResult.AccessToken, Expires = oauthResult.Expires }; tcs.SetResult(tempToken); } else { tcs.SetException(new Exception(oauthResult.Error)); } }); return tcs.Task; }
public abstract void SaveSessionData(AccessTokenData data);
private void OnFacebookAuthenticationFinished(AccessTokenData session) { MessageBox.Show("Facebook authentication succeeded. Expiry date: " + session.Expires); }
private void OnFacebookAuthenticationFinished(AccessTokenData session) { Frame.Navigate(typeof(FacebookAuthentication), session); }
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; }
private void OnFacebookAuthenticationFinished(AccessTokenData session) { var msgbox = new MessageDialog("connecté"); // here the authentication succeeded callback will be received. // put your login logic here }
internal async static void OnFacebookAuthenticationFinished(AccessTokenData session) { fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken); result = await fb.GetTaskAsync("me"); currentUser = new Facebook.Client.GraphUser(result); }
/// <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 = Session.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. } } }
internal async Task <AccessTokenData> LoginAsync(string permissions, bool force, FacebookLoginBehavior loginBehavior) { if (this.LoginInProgress) { throw new InvalidOperationException("Login in progress."); } this.LoginInProgress = true; try { var session = AccessTokenDataCacheProvider.Current.GetSessionData(); if (session == null) { #if WINDOWS // Authenticate var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #else var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #endif FacebookClient client = new FacebookClient(authResult.AccessToken); var parameters = new Dictionary <string, object>(); parameters["fields"] = "id"; var result = await client.GetTaskAsync("me", parameters); var dict = (IDictionary <string, object>)result; session = new AccessTokenData { AccessToken = authResult.AccessToken, Expires = authResult.Expires, FacebookId = (string)dict["id"], }; } else { // Check if we are requesting new permissions bool newPermissions = false; if (!string.IsNullOrEmpty(permissions)) { var p = permissions.Split(','); newPermissions = session.CurrentPermissions.Join(p, s1 => s1, s2 => s2, (s1, s2) => s1).Count() != p.Length; } // Prompt OAuth dialog if force renew is true or // if new permissions are requested or // if the access token is expired. if (force || newPermissions || session.Expires <= DateTime.UtcNow) { #if WINDOWS // Authenticate var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #else var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #endif if (authResult != null) { session.AccessToken = authResult.AccessToken; session.Expires = authResult.Expires; } } } // Set the current known permissions if (!string.IsNullOrEmpty(permissions)) { var p = permissions.Split(','); session.CurrentPermissions = session.CurrentPermissions.Union(p).ToList(); } // Save session data AccessTokenDataCacheProvider.Current.SaveSessionData(session); CurrentAccessTokenData = session; } finally { this.LoginInProgress = false; } return(CurrentAccessTokenData); }
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. Session.ActiveSession.RedirectPageOnSuccess = String.IsNullOrEmpty(Session.AppId) ? "MainPage.xaml" : Session.AppId; return(new Uri("/" + Session.ActiveSession.RedirectPageOnSuccess, UriKind.Relative)); } // Otherwise perform normal launch. return(uri); }
internal async Task<AccessTokenData> LoginAsync(string permissions, bool force, FacebookLoginBehavior loginBehavior) { if (this.LoginInProgress) { throw new InvalidOperationException("Login in progress."); } this.LoginInProgress = true; try { var session = AccessTokenDataCacheProvider.Current.GetSessionData(); if (session == null) { #if WINDOWS // Authenticate var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #else var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #endif FacebookClient client = new FacebookClient(authResult.AccessToken); var parameters = new Dictionary<string, object>(); parameters["fields"] = "id"; var result = await client.GetTaskAsync("me", parameters); var dict = (IDictionary<string, object>)result; session = new AccessTokenData { AccessToken = authResult.AccessToken, Expires = authResult.Expires, FacebookId = (string)dict["id"], }; } else { // Check if we are requesting new permissions bool newPermissions = false; if (!string.IsNullOrEmpty(permissions)) { var p = permissions.Split(','); newPermissions = session.CurrentPermissions.Join(p, s1 => s1, s2 => s2, (s1, s2) => s1).Count() != p.Length; } // Prompt OAuth dialog if force renew is true or // if new permissions are requested or // if the access token is expired. if (force || newPermissions || session.Expires <= DateTime.UtcNow) { #if WINDOWS // Authenticate var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #else var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None, loginBehavior); #endif if (authResult != null) { session.AccessToken = authResult.AccessToken; session.Expires = authResult.Expires; } } } // Set the current known permissions if (!string.IsNullOrEmpty(permissions)) { var p = permissions.Split(','); session.CurrentPermissions = session.CurrentPermissions.Union(p).ToList(); } // Save session data AccessTokenDataCacheProvider.Current.SaveSessionData(session); CurrentAccessTokenData = session; } finally { this.LoginInProgress = false; } return CurrentAccessTokenData; }
async private void OnFacebookAuthenticationFinished(AccessTokenData session) { ShowDialog(session); }
private void OnFacebookAuthenticationFinished(AccessTokenData session) { // here the authentication succeeded callback will be received. }
public abstract void SaveSessionData(AccessTokenData data);