private TryParseOAuthCallbackUrl ( Uri url, FacebookOAuthResult &facebookOAuthResult ) : bool | ||
url | Uri | |
facebookOAuthResult | FacebookOAuthResult | |
리턴 | bool |
private void FBLogin_Navigated(object sender, NavigationEventArgs e) { // whenever the browser navigates to a new url, try parsing the url. // the url may be the result of OAuth 2.0 authentication. var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { // The url is the result of OAuth 2.0 authentication if (oauthResult.IsSuccess) { var accesstoken = oauthResult.AccessToken; FBLogin.IsEnabled = false; accessToken = accesstoken; } else { var errorDescription = oauthResult.ErrorDescription; var errorReason = oauthResult.ErrorReason; } } else { // The url is NOT the result of OAuth 2.0 authentication. } }
private async void FaceBookLoginPageNavigated(object sender, NavigationEventArgs e) { if (FaceBookLoginPage.Visibility == Visibility.Collapsed) return; FacebookOAuthResult oauthResult; var fb = new FacebookClient(); if (!fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } if (oauthResult.IsSuccess) { await ProcessFbOathResult(oauthResult); gridFBLoggedIn.Visibility = Visibility.Visible; FaceBookLoginPage.Visibility = Visibility.Collapsed; Dispatcher.BeginInvoke(() => DataContext = App.ViewModel.UserPreference); FaceBookLoginPage.Visibility = Visibility.Collapsed; gridFBLoggedIn.Visibility = Visibility.Visible; LinkButton.Visibility = Visibility.Collapsed; } else { FaceBookLoginPage.Visibility=Visibility.Collapsed; gridFBLoggedIn.Visibility=Visibility.Collapsed; LinkButton.Visibility=Visibility.Visible; } }
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { // whenever the browser navigates to a new url, try parsing the url // the url may be the result of OAuth 2.0 authentication. FacebookOAuthResult oauthResult; var fb = new FacebookClient(); if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { // The url is the result of OAuth 2.0 authentication. if (oauthResult.IsSuccess) { // we got the code here fb.PostCompleted+= (o, args) => { // make sure to check that no error has occurred. if (args.Error != null) { // make sure to access ui stuffs on the correct thread. Dispatcher.BeginInvoke( () => { MessageBox.Show(args.Error.Message); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); }); } else { var result = (IDictionary<string, object>)args.GetResultData(); var accessToken = (string)result["access_token"]; // make sure to access ui stuffs on the correct thread. Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/FacebookInfoPage.xaml?access_token=" + accessToken, UriKind.Relative))); } }; fb.PostAsync("oauth/access_token",new { client_id = AppId, client_secret = AppSecret, redirect_uri = RedirectUri, code = oauthResult.Code }); } else { // the user clicked don't allow or some other error occurred. MessageBox.Show(oauthResult.ErrorDescription); } } else { // The url is NOT the result of OAuth 2.0 authentication. } }
private void wb_Navigated(object sender, WebBrowserNavigatedEventArgs e) { var fb=new FacebookClient(); if (fb.TryParseOAuthCallbackUrl(e.Url, out result)) { if (result.IsSuccess) { this.Hide(); } else { var errorDescription = result.ErrorDescription; var errorReason = result.ErrorReason; } } }
private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { // whenever the browser navigates to a new url, try parsing the url. // the url may be the result of OAuth 2.0 authentication. var fb = new Facebook.FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { // The url is the result of OAuth 2.0 authentication if (oauthResult.IsSuccess) { Settings1.Default.FacebookToken = oauthResult.AccessToken; fb.AccessToken = Settings1.Default.FacebookToken; //now retrieve all connected accounts and if there are more than one then display combobox allows user to choose which account he want to use JsonObject fbAccounts = (JsonObject)fb.Get("/me/accounts"); ListItem <string> item = new ListItem <string>(Strings.FacebookLoginWindow_DefaultAccount, oauthResult.AccessToken); cmbFacebookAccounts.Items.Add(item); foreach (dynamic account in (IEnumerable)fbAccounts["data"]) { item = new ListItem <string>(account["name"], account["access_token"]); cmbFacebookAccounts.Items.Add(item); } if (cmbFacebookAccounts.Items.Count == 1) { DialogResult = true; Close(); } else { cmbFacebookAccounts.SelectedIndex = 0; webBrowser.Visibility = Visibility.Collapsed; pnlChooseAccount.Visibility = Visibility.Visible; } } else { //var errorDescription = oauthResult.ErrorDescription; //var errorReason = oauthResult.ErrorReason; DialogResult = false; Close(); } } else { // The url is NOT the result of OAuth 2.0 authentication. } }
public FacebookOAuthResponse ParseResponse(HttpContext context) { var stateCookie = context.Request.Cookies[StateCookieName]; context.Response.Cookies[FacebookAuthenticationProvider.StateCookieName].Expires = DateTime.Now.AddSeconds(-60); Guid cookieStateValue; Guid querystringStateValue; FacebookOAuthResult facebookResult; var client = new FacebookClient(); if (stateCookie == null || !Guid.TryParse(stateCookie.Value, out cookieStateValue)) { throw new AuthenticationException("State cookie not set"); } if (!client.TryParseOAuthCallbackUrl(context.Request.Url, out facebookResult)) { throw new AuthenticationException(string.Format("Request is not a valid Facebook OAuthCallbackUrl {0}", context.Request.Url)); } if (!Guid.TryParse(facebookResult.State, out querystringStateValue) || cookieStateValue != querystringStateValue) { throw new AuthenticationException(string.Format("Response state value {0} does not equal state cookie {1}", querystringStateValue, cookieStateValue)); } var url = string.Format(TokenUrl, FacebookConfig.FacebookAppId, context.Request.Url.GetLeftPart(UriPartial.Authority), FacebookConfig.FacebookAppSecret, facebookResult.Code); var response = new WebClient().DownloadString(new Uri(url)); var p = HttpUtility.ParseQueryString(response); var token = p["access_token"]; var expires = int.Parse(p["expires"]); client.AccessToken = token; dynamic me = client.Get("me"); return new FacebookOAuthResponse { Token = token, ExpirySeconds = expires, User = me }; }
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e) { try { // whenever the browser navigates to a new url, try parsing the url. // the url may be the result of OAuth 2.0 authentication. var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)) { // The url is the result of OAuth 2.0 authentication if (oauthResult.IsSuccess) { var accesstoken = oauthResult.AccessToken; //webBrowser.Hide(); Wall wall = new Wall(accesstoken.ToString()); wall.Show(); this.Hide(); } else { var errorDescription = oauthResult.ErrorDescription; var errorReason = oauthResult.ErrorReason; } } else { // The url is NOT the result of OAuth 2.0 authentication. } } catch (Exception ex) { throw; } finally { } }
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { // whenever the browser navigates to a new url, try parsing the url // the url may be the result of OAuth 2.0 authentication. var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)) { // The url is the result of OAuth 2.0 authentication. this.FacebookOAuthResult = oauthResult; this.DialogResult = FacebookOAuthResult.IsSuccess ? DialogResult.OK : DialogResult.No; } else { // The url is NOT the result of OAuth 2.0 authentication. this.FacebookOAuthResult = null; } }
//hämtar accesstoken efter login private void CheckLogin(object sender, WebBrowserDocumentCompletedEventArgs e) { var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var accesstoken = oauthResult.AccessToken; fbEvents.Token = accesstoken; fbEvents.UserName(accesstoken); this.Visible = false; } else { var errorDescription = oauthResult.ErrorDescription; var errorReason = oauthResult.ErrorReason; } } }
private void FacebookBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { FacebookOAuthResult oauthResult; if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } if (oauthResult.IsSuccess) { var accessToken = oauthResult.AccessToken; FacebookWebBrowser.Visibility = System.Windows.Visibility.Collapsed; LoginSucceded(accessToken); } else { // user cancelled MessageBox.Show(oauthResult.ErrorDescription); } }
public ActionResult LoginRetorno() { var _fb = new FacebookClient(); FacebookOAuthResult oauthResult; //Pega o Code if (!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult)) { //erro } if (oauthResult.IsSuccess) { //Pega o Access Token "permanente" Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("client_id", ConfigurationManager.AppSettings["FacebookAppId"]); parameters.Add("redirect_uri", "http://localhost:2780/home/LoginRetorno"); parameters.Add("client_secret", ConfigurationManager.AppSettings["FacebookAppSecret"]); parameters.Add("code", oauthResult.Code); dynamic result = _fb.Get("/oauth/access_token", parameters); var accessToken = result.access_token; //TODO:Guardar no banco Session["accessToken"] = accessToken; //Exemplo de uso var client = new FacebookClient(accessToken); dynamic me = client.Get("me"); ViewBag.Usuario = me.ToString(); ViewBag.MostraForm = true; } else { // user cancelled } return View("Index"); }
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)) { // The url is the result of OAuth 2.0 authentication if (oauthResult.IsSuccess) { var accesstoken = oauthResult.AccessToken; Data.Set("token", FB.ExtendToken(accesstoken)); next.Show(); this.Close(); } else { var errorDescription = oauthResult.ErrorDescription; var errorReason = oauthResult.ErrorReason; } } }
/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="username">The username.</param> /// <param name="returnUrl">The return URL.</param> /// <returns></returns> public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl ) { var fbClient = new FacebookClient(); FacebookOAuthResult oAuthResult; if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess ) { try { var redirectUri = new Uri( GetRedirectUrl( request ) ); dynamic parameters = new ExpandoObject(); parameters.client_id = GetAttributeValue( "AppID" ); parameters.client_secret = GetAttributeValue( "AppSecret" ); parameters.redirect_uri = redirectUri.AbsoluteUri; parameters.code = oAuthResult.Code; dynamic result = fbClient.Post( "oauth/access_token", parameters ); string accessToken = result.access_token; fbClient = new FacebookClient( accessToken ); dynamic me = fbClient.Get( "me" ); string facebookId = "FACEBOOK_" + me.id.ToString(); UserLogin user = null; var rockContext = new RockContext(); rockContext.WrapTransaction( () => { // query for matching id in the user table var userLoginService = new UserLoginService( rockContext ); user = userLoginService.GetByUserName( facebookId ); // if no user was found see if we can find a match in the person table if ( user == null ) { try { var familyChanges = new List<string>(); var familyMemberChanges = new List<string>(); var PersonChanges = new List<string>(); // determine if we can find a match and if so add an user login record // get properties from Facebook dynamic object string lastName = me.last_name.ToString(); string firstName = me.first_name.ToString(); string email = me.email.ToString(); var personService = new PersonService( rockContext ); var person = personService.Queryable( "Aliases" ).FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email ); if ( person != null ) { // since we have the data enter the birthday from Facebook to the db if we don't have it yet DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() ); if ( person.BirthDay == null ) { History.EvaluateChange( PersonChanges, "Birth Date", person.BirthDate, person.BirthDate ); person.BirthDate = birthdate; rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, PersonChanges ); } } else { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; person.RecordStatusValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id; person.FirstName = me.first_name.ToString(); person.LastName = me.last_name.ToString(); person.Email = me.email.ToString(); if ( me.gender.ToString() == "male" ) person.Gender = Gender.Male; else if ( me.gender.ToString() == "female" ) person.Gender = Gender.Female; else person.Gender = Gender.Unknown; person.BirthDate = Convert.ToDateTime( me.birthday.ToString() ); person.EmailPreference = EmailPreference.EmailAllowed; GroupService.SaveNewFamily( rockContext, person, null, false ); } user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true ); } catch ( Exception ex ) { string msg = ex.Message; // TODO: probably should report something... } } else { // TODO: Show label indicating inability to find user corresponding to facebook id } } ); if ( user != null ) { username = user.UserName; returnUrl = oAuthResult.State; return true; } else { username = string.Empty; returnUrl = string.Empty; return false; } } catch ( FacebookOAuthException oae ) { string msg = oae.Message; // TODO: Add error handeling // Error validating verification code. (usually from wrong return url very picky with formatting) // Error validating client secret. // Error validating application. } } username = null; returnUrl = null; return false; }
public override void OnPageFinished(WebView view, string url) { base.OnPageFinished (view, url); var fb = new FacebookClient (); FacebookOAuthResult oauthResult; if (!fb.TryParseOAuthCallbackUrl (new Uri (url), out oauthResult)) { return; } if (oauthResult.IsSuccess) { // Facebook Granted Token var accessToken = oauthResult.AccessToken; LoginSucceded (accessToken); } else { // user cancelled login LoginSucceded (string.Empty); } }
private void FaceBookLoginPageNavigated(object sender, NavigationEventArgs e) { if (FaceBookLoginPage.Visibility == Visibility.Collapsed) return; FacebookOAuthResult oauthResult; var fb = new FacebookClient(); if (!fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } if (oauthResult.IsSuccess) { if (ProcessFbOathResult(oauthResult) == 1) { Dispatcher.BeginInvoke(() => MessageBox.Show("Er is een fout opgetreden tijdens de authenticatie")); } gridFBLoggedIn.Visibility = Visibility.Visible; FaceBookLoginPage.Visibility = Visibility.Collapsed; Dispatcher.BeginInvoke(() => DataContext = App.ViewModel.UserPreference); } else { MainPivot_OnSelectionChanged(null, null); } }
public void PopulateAccessToken(string code) { if (!TokenExists()) { string accessToken = null; var fb = new FacebookClient(); FacebookOAuthResult oauthResult; if (fb.TryParseOAuthCallbackUrl(HttpContext.Current.Request.Url, out oauthResult)) { // The url is the result of OAuth 2.0 authentication if (oauthResult.IsSuccess) { accessToken = oauthResult.AccessToken; } else { var errorDescription = oauthResult.ErrorDescription; var errorReason = oauthResult.ErrorReason; } } else { // The url is NOT the result of OAuth 2.0 authentication. } if (string.IsNullOrWhiteSpace(accessToken)) accessToken = GetAccessToken(code); _storage.Store(StoreKey, accessToken); } }
public void FacebookCredentialResult( string response, FacebookClient session, BindResult result ) { // make sure we got a valid access token FacebookOAuthResult oauthResult; if( session.TryParseOAuthCallbackUrl (new Uri ( response ), out oauthResult) == true ) { if ( oauthResult.IsSuccess ) { // now attempt to get their basic info FacebookClient fbSession = new FacebookClient( oauthResult.AccessToken ); string infoRequest = FacebookManager.Instance.CreateInfoRequest( ); fbSession.GetTaskAsync( infoRequest ).ContinueWith( t => { // if there was no problem, we are logged in and can send this up to Rock if ( t.IsFaulted == false || t.Exception == null ) { // now login via rock with the facebook credentials to verify we're good RockApi.Post_Auth_FacebookLogin( t.Result, delegate(System.Net.HttpStatusCode statusCode, string statusDescription) { if( Rock.Mobile.Network.Util.StatusInSuccessRange( statusCode ) == true ) { UserID = "facebook_" + FacebookManager.Instance.GetUserID( t.Result ); RockPassword = ""; AccessToken = oauthResult.AccessToken; AccountType = BoundAccountType.Facebook; // save! SaveToDevice( ); result( true ); } else { result( false ); } }); } else { // didn't work out. result( false ); } } ); } else { result( false ); } } else { // didn't work out. result( false ); } }
/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="username">The username.</param> /// <param name="returnUrl">The return URL.</param> /// <returns></returns> public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl ) { var fbClient = new FacebookClient(); FacebookOAuthResult oAuthResult; if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess ) { try { var redirectUri = new Uri( GetRedirectUrl( request ) ); dynamic parameters = new ExpandoObject(); parameters.client_id = GetAttributeValue( "AppID" ); parameters.client_secret = GetAttributeValue( "AppSecret" ); parameters.redirect_uri = redirectUri.AbsoluteUri; parameters.code = oAuthResult.Code; dynamic result = fbClient.Post( "oauth/access_token", parameters ); string accessToken = result.access_token; fbClient = new FacebookClient( accessToken ); dynamic me = fbClient.Get( "me" ); string facebookId = "FACEBOOK_" + me.id.ToString(); // query for matching id in the user table var userLoginService = new UserLoginService(); var user = userLoginService.GetByUserName( facebookId ); // if not user was found see if we can find a match in the person table if ( user == null ) { try { // determine if we can find a match and if so add an user login record // get properties from Facebook dynamic object string lastName = me.last_name.ToString(); string firstName = me.first_name.ToString(); string email = me.email.ToString(); var personService = new PersonService(); var person = personService.Queryable().FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email ); if ( person != null ) { // since we have the data enter the birthday from Facebook to the db if we don't have it yet DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() ); if ( person.BirthDay == null ) { person.BirthDate = birthdate; personService.Save( person, person.Id ); } } else { var dvService = new DefinedValueService(); person = new Person(); person.IsSystem = false; person.RecordTypeValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ); person.RecordStatusValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ); person.FirstName = me.first_name.ToString(); person.LastName = me.last_name.ToString(); person.Email = me.email.ToString(); if ( me.gender.ToString() == "male" ) person.Gender = Gender.Male; else if ( me.gender.ToString() == "female" ) person.Gender = Gender.Female; else person.Gender = Gender.Unknown; person.BirthDate = Convert.ToDateTime( me.birthday.ToString() ); person.DoNotEmail = false; personService.Add( person, null ); personService.Save( person, null ); } user = userLoginService.Create( person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true, person.Id ); } catch ( Exception ex ) { string msg = ex.Message; // TODO: probably should report something... } // TODO: Show label indicating inability to find user corresponding to facebook id } username = user.UserName; returnUrl = oAuthResult.State; return true; } catch ( FacebookOAuthException oae ) { string msg = oae.Message; // TODO: Add error handeling // Error validating verification code. (usually from wrong return url very picky with formatting) // Error validating client secret. // Error validating application. } } username = null; returnUrl = null; return false; }
public bool HasFacebookResponse( string response, FacebookClient session ) { // if true is returned, there IS a response, so the caller can call the below FacebookCredentialResult FacebookOAuthResult oauthResult; return session.TryParseOAuthCallbackUrl( new Uri( response ), out oauthResult ); }