public ActionResult FbAuth(string returnUrl) { var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); // Build the Return URI form the Request Url var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Url.Action("FbAuth", "Account"); dynamic result = client.Get("/oauth/access_token", new { client_id = ConfigurationManager.AppSettings["FacebookAppId"], redirect_uri = redirectUri.Uri.AbsoluteUri, client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"], code = oauthResult.Code, }); // Read the auth values string accessToken = result.access_token; DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); dynamic me = client.Get("/me", new { fields = "first_name,last_name,email", access_token = accessToken }); // Read the Facebook user values long facebookId = Convert.ToInt64(me.id); string firstName = me.first_name; string lastName = me.last_name; string email = me.email; // Add the user to our persistent store var userService = new UserService(); userService.AddOrUpdateUser(new User { Id = facebookId, FirstName = firstName, LastName = lastName, Email = email, AccessToken = accessToken, Expires = expires }); // Set the Auth Cookie FormsAuthentication.SetAuthCookie(email, false); // Redirect to the return url if availible if (String.IsNullOrEmpty(returnUrl)) { return Redirect("/App"); } else { return Redirect(returnUrl); } }
private async void Button_Click_1(object sender, RoutedEventArgs e) { var result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(String.Format(oauthUrl, facebookAppId, redirectUri, facebookAuthScope)), new Uri(redirectUri)); if (result.ResponseStatus == WebAuthenticationStatus.Success) { var client = new FacebookClient(); var session = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData)); AccessToken.Text = session.AccessToken; } }
public static FacebookUserModel FacebookHandshake(string redirectUri, HttpRequestBase request) { var model = new FacebookUserModel(); var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(request.Url); // Build the Return URI form the Request Url // Exchange the code for an access token dynamic result = client.Get("/oauth/access_token", new { client_id = SocialMediaConnectConstants.AppId, redirect_uri = redirectUri, client_secret = SocialMediaConnectConstants.AppSecret, code = oauthResult.Code , }); // Read the auth values string accessToken = result.access_token; //If needed you can add the access token to a cookie for pulling additional inforamtion out of Facebook //DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); //HttpCookie myCookie = HttpContext.Current.Request.Cookies["accessToken"] ?? new HttpCookie("accessToken"); //myCookie.Values["value"] = accessToken; //myCookie.Expires = expires; //HttpContext.Current.Response.Cookies.Add(myCookie); // Get the user's profile information dynamic me = client.Get("/me", new { fields = "name,picture,first_name,last_name,email,id,birthday,location,gender", access_token = accessToken }); // Read the Facebook user values model.UserId = me.id; model.FirstName = me.first_name; model.LastName = me.last_name; model.Email = me.email; model.ProfileImageUrl = ExtractImageUrl(me); model.Birthday = me.birthday; model.Gender = me.gender; model.Location = me.location["name"].ToString(); return model; }
public string ParseAuthenticationResult(FacebookClient fb, WebAuthenticationResult result) { switch (result.ResponseStatus) { case WebAuthenticationStatus.ErrorHttp: return "Error"; case WebAuthenticationStatus.Success: var oAuthResult = fb.ParseOAuthCallbackUrl(new Uri(result.ResponseData)); return oAuthResult.AccessToken; case WebAuthenticationStatus.UserCancel: return "Operation aborted"; } return null; }
void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { if (facebookAppId == "your Facebook AppId here") { throw new ArgumentException("You must set the facebookAppId variable to your own Facebook App Id."); } if (e.Uri.ToString().StartsWith(redirectUri)) { var client = new FacebookClient(); var result = client.ParseOAuthCallbackUrl(e.Uri); var accessToken = result.AccessToken; var navUri = String.Format("/Welcome.xaml?access_token={0}", accessToken); NavigationService.Navigate(new Uri(navUri, UriKind.Relative)); } }
private async Task<FacebookOAuthResult> PromptOAuthDialog(string permissions, WebAuthenticationOptions options) { // Use WebAuthenticationBroker to launch server side OAuth flow Uri startUri = this.GetLoginUrl(permissions); Uri endUri = new Uri("https://www.facebook.com/connect/login_success.html"); var result = await WebAuthenticationBroker.AuthenticateAsync(options, startUri, endUri); if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { throw new InvalidOperationException(); } else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel) { throw new InvalidOperationException(); } var client = new FacebookClient(); var authResult = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData)); return authResult; }
public ActionResult Index() { //var data = ExamineeService.GetList(); // Session["dataindex"] = data; //Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. //Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. //Response.AppendHeader("Expires", "0"); // Proxies. ViewBag.Title = "Jbart Academy - cuộc thi ảnh"; // var data = UserService.GetList(); //if (SessionManagement.GetSessionReturnToString("loginFBmode") != null) //{ // Session["loginFBmode"] = null; // return RedirectToAction("Profile", "User"); //} //if (Request.QueryString["code"] != null) //{ // // return Redirect("http://cuocthijba.com/User/Profile"); // return Redirect("http://localhost:1655/User/Profile"); //} if (SessionManagement.GetSessionReturnToString("loginFBmode") != null) { var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Url.Action("Index", "Home"); try { string SecId = ConfigurationManager.AppSettings["Facbook_SecID"].ToString(); string AppId = ConfigurationManager.AppSettings["Facebook_AppID"].ToString();/// var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); dynamic result = client.Get("/oauth/access_token", new { client_id = AppId, redirect_uri = redirectUri.Uri.AbsoluteUri, client_secret = SecId, code = oauthResult.Code, }); // Read the auth values redirectUri.Path = result.redirect_uri; string accessToken = result.access_token; Session["access_token"] = accessToken; DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); // Get the user's profile information dynamic me = client.Get("/me", new { fields = "first_name,last_name,email", access_token = accessToken }); User u = new CoreData.User(); long fbiduser = long.Parse(me.id); var userFBexist = UserService.GetOneByLINQ(c => c.FacebookUserID.Equals(fbiduser)); if (userFBexist == null) { u.Active = true; u.UserName = me.first_name; u.Name = me.last_name + " " + me.first_name; u.Password = "******"; u.Email = me.email; u.GroupIDExt = 1; u.FacebookUserID = fbiduser; var uid = UserService.Save(u); Session["access_token"] = result.access_token; Session["UserName"] = u.UserName; Session["UserID"] = uid; Session["UserGroup"] = 1; Session["ExamineeID"] = ExamineeService.GetOneByLINQ(c => c.UserID.Equals(uid)).ID; Session["loginFBmode"] = null; } else { Session["access_token"] = result.access_token; Session["UserName"] = userFBexist.UserName; Session["UserID"] = userFBexist.ID; Session["UserGroup"] = 1; Session["ExamineeID"] = ExamineeService.GetOneByLINQ(c => c.UserID.Equals(userFBexist.ID)).ID; Session["loginFBmode"] = null; } } catch { Session["loginFBmode"] = null; } return RedirectToAction("Profile","User"); } //HttpContext..Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); //HttpContext.Current.Response.Cache.SetValidUntilExpires(false); //HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); //HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); //HttpContext.Current.Response.Cache.SetNoStore(); return View(); }
public virtual ActionResult Facebook(string returnUrl) { try { var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); // Build the Return URI form the Request Url var redirectUri = new UriBuilder(Url.Action("facebook", "join", new { InPopUp }, "http")); // Exchange the code for an access token dynamic result = client.Get("/oauth/access_token", new { client_id = ConfigurationManager.AppSettings["FacebookAppId"], redirect_uri = redirectUri.Uri.AbsoluteUri, client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"], code = oauthResult.Code, }); // Read the auth values string accessToken = result.access_token; DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); var fbClient = new FacebookClient(accessToken); dynamic facebookUser = fbClient.Get("me"); if (facebookUser == null) { this.StoreError("There was a problem connecting to your Facebook account"); return RedirectToAction("Signup", InPopUp); } //Check if this user already exists. If so login and redirect to the homepage var userId = CheckConnectedAccountUserExists(facebookUser.username, AuthenticationServices.FACEBOOK, accessToken, null); if (userId != Guid.Empty) { CookieHelpers.WriteCookie("lc", "uid", userId.ToString()); RecordTheLogin(userId); if (InPopUp) return RedirectToAction("CloseAndRefresh", "Account"); //this.StoreInfo("The Facebook account you used is already associated with an Epilogger account. We have logged you in."); return RedirectToAction("Index", "Home", new { area = "" }); } var model = new CreateAccountModel() { AuthToken = accessToken, AuthScreenname = facebookUser.username, FirstName = facebookUser.first_name, LastName = facebookUser.last_name, DisplayProfileImage = FacebookHelper.GetProfilePictureWithSize(accessToken, "large"), ProfileImage = FacebookHelper.GetProfilePicture(accessToken), ServiceUserName = facebookUser.username, AuthService = "facebook", InPopUp = InPopUp }; //Continue to Step 2 return View(model); } catch (Exception) { this.StoreError("There was a problem connecting to your Facebook account"); return RedirectToAction("Signup"); } }
public ActionResult FbAuth(string returnUrl) { var client = new FacebookClient(); try { var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); // Build the Return URI form the Request Url var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Url.Action("FbAuth", "Account"); //Get the Public Uri due to apphabor getting all "cloudy" with ports var urlHelper = new UrlHelper(Request.RequestContext); var publicUrl = urlHelper.ToPublicUrl(redirectUri.Uri); // Exchange the code for an access token dynamic result = client.Get("/oauth/access_token", new { client_id = ConfigurationManager.AppSettings["FacebookAppId"], redirect_uri = publicUrl, client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"], code = oauthResult.Code, }); // Read the auth values string accessToken = result.access_token; DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); // Get the user's profile information dynamic me = client.Get("/me", new { fields = "first_name,last_name,email", access_token = accessToken }); //Instantiate FbModel var model = new FbModel(); // Read the Facebook user values model.FacebookId = Convert.ToInt64(me.id); model.FirstName = me.first_name; model.LastName = me.last_name; model.Email = me.email; // Add the user to our persistent store var user = AccountService.AddOrUpdateFacebookUser(model); //Check if the account requires the password to be set if (string.IsNullOrEmpty(user.Email)) { return RedirectToAction("RegisterFacebook", "Account", new { @code = user.AccountHash }); } else { AuthenticateUser(user.Id, user.FirstName, user.LastName, user.Email, user.FacebookId, user.AccessToken); return RedirectToAction("Index", "Home"); } } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } return RedirectToAction("Content", "Error"); }
public async Task<SocialCreds> FacebookLogin() { string _facebookAppId = "189779734480590"; string _permissions = "user_about_me, user_birthday, email"; // Set your permissions here FacebookClient _fb = new FacebookClient(); var redirectUrl = "https://www.facebook.com/connect/login_success.html"; try { var loginUrl = _fb.GetLoginUrl(new { client_id = _facebookAppId, redirect_uri = redirectUrl, scope = _permissions, display = "popup", response_type = "token" }); var endUri = new Uri(redirectUrl); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, loginUrl, endUri); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var callbackUri = new Uri(WebAuthenticationResult.ResponseData.ToString()); var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(callbackUri); var accessToken = facebookOAuthResult.AccessToken; if (String.IsNullOrEmpty(accessToken)) { // User is not logged in, they may have canceled the login return null; } else { // User is logged in and token was returned dynamic parameters = new System.Dynamic.ExpandoObject(); parameters.access_token = accessToken; parameters.fields = "id"; dynamic result = await _fb.GetTaskAsync("me", parameters); parameters.id = result.id; return new SocialCreds { ProviderType = "Facebook", AccessToken = accessToken, ID = result.id }; } } else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString()); } else { // The user canceled the authentication return null; } } catch (Exception ex) { // // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here. // throw ex; } }
public ActionResult FBAuth(string returnUrl) { var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); // Build the Return URI form the Request Url var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Url.Action("FbAuth","Account"); dynamic result = client.Get("/oauth/access_token", new //get the facebook token { client_id = Settings.Settings.FacebookAppId, redirect_uri = Settings.Settings.FacebookCallbackURL, client_secret = Settings.Settings.FacebookAppSecret, code = oauthResult.Code, }); if (result == null) { return RedirectToAction("ExternalLoginFailure"); } string accessToken = result.access_token; string token = FacebookAPI.GetLongtermFbToken(accessToken); //get a 2month token FacebookToken = accessToken; Provider = "facebook"; dynamic me = client.Get("/me", //get some basic user info new { fields = "first_name,last_name,email", access_token = accessToken }); if (OAuthWebSecurity.Login("facebook",me.id, createPersistentCookie: false)) { string username = OAuthWebSecurity.GetUserName("facebook", me.id); int userId = WebSecurity.GetUserId(username); FacebookScheduler scheduler = new FacebookScheduler(); //run any undone task scheduler.RunScheduler(token, userId); return RedirectToLocal(returnUrl); } if (User.Identity.IsAuthenticated) { // If the current user is logged in add the new account DatabaseCallsApi _api = new DatabaseCallsApi(); var username = OAuthWebSecurity.GetUserName("facebook", me.id); _api.AddOrUpdateService(WebSecurity.CurrentUserId, "facebook", token); OAuthWebSecurity.CreateOrUpdateAccount("facebook",me.id, WebSecurity.CurrentUserName.ToString()); return RedirectToLocal(returnUrl); } else { // User is new, ask for their desired membership name CheckChanceState(); string loginData = OAuthWebSecurity.SerializeProviderUserId("facebook", me.id); ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData("facebook").DisplayName; ViewBag.ReturnUrl = returnUrl; return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = me.email, ExternalLoginData = loginData, Email = me.email }); } }
public ActionResult FbAuth(string returnUrl) { var client = new FacebookClient(); var oauthResult = client.ParseOAuthCallbackUrl(Request.Url); // Build the Return URI form the Request Url var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Url.Action("FbAuth", "Login"); // Exchange the code for an access token dynamic result = client.Get("/oauth/access_token", new { client_id = ConfigurationManager.AppSettings["FacebookAppId"], redirect_uri = redirectUri.Uri.AbsoluteUri, client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"], code = oauthResult.Code, }); // Read the auth values string accessToken = result.access_token; DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires)); // Get the user's profile information dynamic me = client.Get("/me", new { fields = "first_name,last_name,email,gender", access_token = accessToken }); // Read the Facebook user values string facebookId = me.id; string firstName = me.first_name; string lastName = me.last_name; string email = me.email; string gender = me.gender; // Add the user to our persistent store using (var unitOfWork = UnitOfWorkFactory.BeginNew()) { try { var existingMember = unitOfWork.MemberRepository.FindMemberByFBId(facebookId); if (existingMember != null) { existingMember.Email = email; existingMember.FBAccessToken = accessToken; existingMember.FBTokenExpiresAt = expires; } else { unitOfWork.MemberRepository.Add( new Member { Id = facebookId, FirstName = firstName, LastName = lastName, Email = email, FBAccessToken = accessToken, FBTokenExpiresAt = expires, Gender = gender ?? AppConstants.Unknown }); } unitOfWork.Commit(); } catch (Exception exception) { unitOfWork.Rollback(); } } Session["UserId"] = facebookId; // Set the Auth Cookie FormsAuthentication.SetAuthCookie(email, false); //string adminIds = ConfigurationManager.AppSettings["MooreMarketAdmin"]; //if (!string.IsNullOrEmpty(adminIds) // && adminIds.Contains(facebookId)) //{ // return Redirect("/Admin/Index"); //} //return Redirect("/Market/WantToBuy"); return Redirect("/Market/Index"); }
private async void Facebook_Tapped(object sender, TappedRoutedEventArgs e) { //Turning ProgressBar ON dataBindingSource.progressBarIsIndeterminate = true; //Setting appID and user permissions string _facebookAppId = "135066233237101"; string _permissions = "user_about_me,email"; //Initialising the FacebookClient Class Object FacebookClient _fb = new FacebookClient(); var redirectUrl = "https://www.facebook.com/connect/login_success.html"; try { var loginUrl = _fb.GetLoginUrl(new { client_id = _facebookAppId, redirect_uri = redirectUrl, scope = _permissions, display = "popup", response_type = "token" }); var endUri = new Uri(redirectUrl); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, loginUrl, endUri); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var callbackUri = new Uri(WebAuthenticationResult.ResponseData.ToString()); var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(callbackUri); var accessToken = facebookOAuthResult.AccessToken; if (String.IsNullOrEmpty(accessToken)) { MessageDialog errorDialog = new MessageDialog("Please Login to your Account! Click on the Facebook LogIn"); errorDialog.Commands.Add(new UICommand("OK")); errorDialog.DefaultCommandIndex = 0; await errorDialog.ShowAsync(); } else { // User is logged in and token was returned LoginSucceded(accessToken,_fb); } } else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { dataBindingSource.progressBarIsIndeterminate = false; var messageBox = new MessageDialog("Could not connect to the network.Please check your internet connection"); messageBox.Commands.Add(new UICommand("OK")); messageBox.DefaultCommandIndex = 0; await messageBox.ShowAsync(); //TO DO : Write a stub to push error logs onto the database } else { // The user canceled the authentication dataBindingSource.progressBarIsIndeterminate = false; } } catch (Exception ex) { throw ex; } }
private async Task<FacebookOAuthResult> PromptOAuthDialog(string permissions, WebAuthenticationOptions options, FacebookLoginBehavior loginBehavior) { #if !WINDOWS if (loginBehavior != FacebookLoginBehavior.LoginBehaviorWebViewOnly) { throw new NotImplementedException("Following login behavior is not supported on Windows Phone: " + loginBehavior.ToString()); } #endif // Use WebviewAuthentication to launch server side OAuth flow Uri startUri = await this.GetLoginUrl(permissions); Uri endUri = new Uri("https://www.facebook.com/connect/login_success.html"); WebAuthenticationResult result = null; #if WINDOWS if (loginBehavior == FacebookLoginBehavior.LoginBehaviorWebAuthenticationBroker) { result = await WebAuthenticationBroker.AuthenticateAsync(options, startUri, endUri); if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { throw new HttpRequestException("An Http error happened. Error Code: " + result.ResponseStatus.ToString()); } else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel) { throw new FacebookOAuthException("Facebook.Client: User cancelled login in WebAuthBroker"); } } #endif var client = new FacebookClient(); var authResult = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData)); return authResult; }