protected void Page_Load(object sender, EventArgs e) { var url = HttpContext.Current.Request.Url; FacebookOAuthResult oauthResult; var oauthClient = new FacebookOAuthClient { AppId = AppId, AppSecret = AppSecret, RedirectUri = new Uri(_silverlightFacebookCallback) }; if (oauthClient.TryParseResult(url, out oauthResult)) { if (oauthResult.IsSuccess) { var result = (IDictionary<string, object>)oauthClient.ExchangeCodeForAccessToken(oauthResult.Code); AccessToken = result["access_token"].ToString(); Label1.Text = AccessToken; } else { ErrorDescription = oauthResult.ErrorDescription; } Response.Cache.SetCacheability(HttpCacheability.NoCache); } else { Response.Redirect("~/"); } }
public static void handleOAuthResult(HttpRequest request, int id) { FacebookOAuthResult oAuthResult; if (FacebookOAuthResult.TryParse(request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { string code = request.Params["code"]; FacebookOAuthClient oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl + "/" + id + "/"); oAuthClient.AppId = ConfigurationManager.AppSettings["Facebook_API_Key"]; oAuthClient.AppSecret = ConfigurationManager.AppSettings["Facebook_API_Secret"]; dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; FacebookClient facebookClient = new FacebookClient(accessToken); dynamic me = facebookClient.Get("me"); long facebookId = Convert.ToInt64(me.id); var facebookService = new FacebookService(); FacebookUser fbUser = facebookService.AddFacebookUser(facebookId, accessToken, me.name, me.gender); HttpContext.Current.Session["FBUser"] = fbUser; var _publishedArticleService = new PublishedArticleService(); var article = _publishedArticleService.GetPublishedArticle(id); System.Web.HttpContext.Current.Response.Redirect("/Blog/Details/" + article.headline.Replace(" ", "_") + "/" + article.articleId + "/"); } } }
public ActionResult Callback(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); var account = Accounts.Get().Where(Accounts.Columns.ForeignID, Actions.Equal, facebookId).SelectOne(); if (account == null) { account = new Account { FBKey = accessToken, Name = me.name, ForeignID = facebookId.ToString() }; account.Insert(); } else { account.FBKey = accessToken; account.Name = me.name; account.Update(); } dynamic pages = fbClient.Get("me/accounts"); foreach (var p in pages.data) { FBPage page = FBPages.Get().Where(FBPages.Columns.ForeignID, Actions.Equal, p.id).SelectOne(); if (page == null) { page = new FBPage { ForeignID = p.id, Name = p.name, Token = p.access_token }; page.Insert(); } else { page.Name = p.name; page.Token = p.access_token; page.Update(); } } ViewBag.Name = account.Name; } } return View(); }
public ActionResult OAuth(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); Auth(facebookId.ToString()); //InMemoryUserStore.Add(new FacebookUser //{ // AccessToken = accessToken, // Expires = expiresOn, // FacebookId = facebookId, // Name = (string)me.name, //}); //FormsAuthentication.SetAuthCookie(facebookId.ToString(), false); // prevent open redirection attack by checking if the url is local. //if (Url.IsLocalUrl(state)) //{ // return Redirect(state); //} //else //{ // return RedirectToAction("Index", "Home"); //} return RedirectToAction("Index", "Home"); } } return RedirectToAction("Index", "Home"); }
public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params) { var builder = new UriBuilder(context.Request.GetUrlRewriter()) {Query = "p=" + context.Request["p"]}; var oauth = new FacebookOAuthClient { AppId = KeyStorage.Get("facebookAppID"), AppSecret = KeyStorage.Get("facebookAppSecret"), RedirectUri = builder.Uri }; FacebookOAuthResult result; if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result)) { if (result.IsSuccess) { var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code); var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"])); using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { var graph = FacebookGraph.Deserialize(responseStream); var profile = ProfileFromFacebook(graph); return profile; } } } return LoginProfile.FromError(new Exception(result.ErrorReason)); } //Maybe we didn't query var extendedPermissions = new[] { "email", "user_about_me" }; var parameters = new Dictionary<string, object> { { "display", "popup" } }; if (extendedPermissions.Length > 0) { var scope = new StringBuilder(); scope.Append(string.Join(",", extendedPermissions)); parameters["scope"] = scope.ToString(); } var loginUrl = oauth.GetLoginUrl(parameters); context.Response.Redirect(loginUrl.ToString()); return LoginProfile.FromError(new Exception("Failed to login with facebook")); }
public ActionResult FBOAuth(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(HttpContext.Request.Url, Url.Action("FBOAuth", "Auth")); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { expiresOn = DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); CurrentUser.FacebookToken = accessToken; CurrentUser.FacebookExpiresDateTime = expiresOn; CurrentUser.FacebookId = facebookId; if (string.IsNullOrEmpty(CurrentUser.Name)) CurrentUser.Name = (string)me.name; CurrentUser.Update(); // prevent open redirection attack by checking if the url is local. if (Url.IsLocalUrl(state)) { return Redirect(state); } else { return RedirectToAction("Index", "Home"); } } } return RedirectToAction("Index", "Home"); }
public ActionResult OAuth(string code, string state) { string redirectUri = String.Empty; FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(Config.LoginRedirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; redirectUri = String.Format("{0}?method=fb&token={1}", Config.MembersLoginUrl, tokenResult.access_token); } } return new RedirectResult(redirectUri); }
public static string GetAccessToken(Uri requestUrl, string code) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(requestUrl, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); string redirectUrl = String.Format("{0}://{1}/{2}?method=fblocal", requestUrl.Scheme, requestUrl.Host, "login.aspx"); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); FbContext.Current.AccessToken = tokenResult.access_token; return tokenResult.access_token; } } throw new Exception(); }
/// <summary> /// Creates a facebook session from a signed request. /// </summary> /// <param name="appSecret"> /// The app secret. /// </param> /// <param name="signedRequest"> /// The signed request. /// </param> /// <returns> /// The facebook session. /// </returns> internal static FacebookSession Create(string appSecret, string code) { FacebookOAuthClient client = new FacebookOAuthClient(FacebookApplication.Current); client.RedirectUri = new Uri(FacebookApplication.Current.CanvasUrl); dynamic response = client.ExchangeCodeForAccessToken(code); string accessToken = response.access_token; double expires = Convert.ToDouble(response.expires); var dictionary = new JsonObject { { "access_token", accessToken } }; dictionary["expires"] = DateTimeConvertor.ToUnixTime(DateTime.Now.AddSeconds(expires)); dictionary["sig"] = GenerateSessionSignature(appSecret, dictionary); return(new FacebookSession(dictionary)); }
// // GET: /Account/OAuth/ public ActionResult OAuth(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { string redirectUrl = "http://" + Request.Url.Host + "/Account/OAuth/"; var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); FormsAuthentication.SetAuthCookie(facebookId.ToString(), false); // prevent open redirection attack by checking if the url is local. if (Url.IsLocalUrl(state)) { return Redirect(state); } else { return RedirectToAction("Index", "Home"); } } } return RedirectToAction("Index", "Home"); }
public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params) { var builder = new UriBuilder(context.Request.GetUrlRewriter()) {Query = "p=" + context.Request["p"]}; var oauth = new FacebookOAuthClient { AppId = KeyStorage.Get("facebookAppID"), AppSecret = KeyStorage.Get("facebookAppSecret"), RedirectUri = builder.Uri }; FacebookOAuthResult result; if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result)) { if (result.IsSuccess) { var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code); var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"])); using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { var graph = FacebookGraph.Deserialize(responseStream); var profile = ProfileFromFacebook(graph); return profile; } } } return LoginProfile.FromError(new Exception(result.ErrorReason)); } //Maybe we didn't query var extendedPermissions = new[] { "email", "user_about_me" }; var parameters = new Dictionary<string, object> { { "display", "popup" } }; if (extendedPermissions.Length > 0) { var scope = new StringBuilder(); scope.Append(string.Join(",", extendedPermissions)); parameters["scope"] = scope.ToString(); } var loginUrl = oauth.GetLoginUrl(parameters); context.Response.Redirect(loginUrl.ToString()); return LoginProfile.FromError(new Exception("Failed to login with facebook")); //var client = new FacebookClient // { // ClientIdentifier = KeyStorage.Get("facebookAppID"), // ClientSecret = KeyStorage.Get("facebookAppSecret"), // }; //try //{ // IAuthorizationState authorization = client.ProcessUserAuthorization(new HttpRequestInfo(context.Request)); // if (authorization == null) // { // // Kick off authorization request // var scope = new List<string>() // { // "email,user_about_me", // }; // client.RequestUserAuthorization(scope, null, null); // } // else // { // var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); // using (var response = request.GetResponse()) // { // if (response != null) // using (var responseStream = response.GetResponseStream()) // { // var graph = FacebookGraph.Deserialize(responseStream); // var profile = ProfileFromFacebook(graph); // return profile; // } // } // } //} //catch (ProtocolException e) //{ // if (e.InnerException is WebException) // { // //Read stream // var responce = // new StreamReader((e.InnerException as WebException).Response.GetResponseStream()).ReadToEnd(); // } // throw; //} }
// GET: /Account/OAuth/ public ActionResult OAuth(string code, string state) { FacebookOAuthResult oauthResult; try { //SMap.GetLogger().Trace("Trying to parse request url:\"" + Request.Url + "\""); if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name,gender,first_name,last_name,link,locale,significant_other"); FacebookInfo userFbInfo = new FacebookInfo { FacebookId = Convert.ToInt64(me.id), AccessToken = accessToken, Expires = expiresOn, Name = me.name, First = me.first_name, Last = me.last_name }; if (!IsRegisteredUser(userFbInfo.FacebookId)) { SMap.GetLogger().Application("LOGON: Denying access to " + userFbInfo.Name + ", ID=" + userFbInfo.FacebookId + ". Request=\"" + Request.Url + "\""); //return RedirectToAction("Index", "Home"); return RedirectToAction("NotRegistered"); } else { SMap.GetLogger().Application("Logging " + userFbInfo.Name + " on. Request=\"" + Request.Url + "\""); UpdateUsersFacebookInfo(userFbInfo); // MLW TODO Replace //FormsAuthentication.SetAuthCookie(userFbInfo.FacebookId.ToString(), true); // was false originally // with the following to set timeout property. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userFbInfo.FacebookId.ToString(), true, 10080 /*1 week*/); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); // MLW TODO remove: FBTest(fbClient); // prevent open redirection attack by checking if the url is local. if (Url.IsLocalUrl(state)) { return Redirect(state); } else { return RedirectToAction("Index", "Home"); } } } else { SMap.GetLogger().Debug("Facebook authorization result was false for request url:\"" + Request.Url + "\""); } } else { SMap.GetLogger().Debug("Facebook object could not parse request url:\"" + Request.Url + "\""); } } catch (Exception ex) { SMap.GetLogger().Error("Exception during LogOn for URL:\"" + Request.Url + "\"", ex); } return RedirectToAction("Index", "Home"); }
private static void LogIn(string code, string registrationId) { var settings = ConfigurationManager.GetSection("facebookSettings"); IFacebookApplication fbApp = null; if (settings != null) { fbApp = settings as IFacebookApplication; } FacebookOAuthClient cl = new FacebookOAuthClient(fbApp); FacebookOAuthResult result = null; string url = HttpContext.Current.Request.Url.OriginalString; // verify that there is a code in the url if (FacebookOAuthResult.TryParse(url, out result)) { if (result.IsSuccess) { cl.RedirectUri = new Uri(loginUri); var parameters = new Dictionary<string, object>(); parameters.Add("permissions", "offline_access"); dynamic accessTokenResponse = cl.ExchangeCodeForAccessToken(code, new Dictionary<string, object> { {"redirect_uri", loginUri} }); string token = accessTokenResponse.access_token as string; dynamic me = new FacebookClient(token).Get("me"); int facebookId = Int32.Parse(me.id); Global.Bus.Publish(new FacebookUserAuthenticatedForRegistrationEvent(registrationId, facebookId, code, token)); } } }
private string GetAccessToken(string code) { var cl = new FacebookOAuthClient(FacebookApplication); cl.RedirectUri = GenerateCallbackUri(); cl.AppId = FacebookApplication.AppId; cl.AppSecret = FacebookApplication.AppSecret; var dict = (JsonObject)cl.ExchangeCodeForAccessToken(code, new Dictionary<string, object> { { "permissions", "offline_access" } }); return dict.Values.ElementAt(0).ToString(); }
private static string GetAccessToken(string code) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(ConfigurationManager.AppSettings["RedirectUrl"]); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { DateTimeConvertor.FromUnixTime(tokenResult.expires); } return accessToken; }
public virtual ActionResult FacebookOAuth(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { string redirectUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Url.Action(this.FacebookOAuth()); var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); oAuthClient.RedirectUri = new Uri(redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; //DateTime expiresOn = DateTime.MaxValue; //if (tokenResult.ContainsKey("expires")) //{ // DateTimeConvertor.FromUnixTime(tokenResult.expires); //} FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name,email,first_name,last_name,link,birthday"); long facebookId = Convert.ToInt64(me.id); string faceBookEmailAddress = ((string)me.email).ToString(); string faceBookFirstName = ((string)me.first_name).ToString(); string faceBookLastName = ((string)me.last_name).ToString(); string faceBookLink = ((string)me.link).ToString(); var facebookBirthday = DateTime.Parse((string)me.birthday, new System.Globalization.CultureInfo("en")); var context = ModelFactory.GetUnitOfWork(); var mRepo = ModelFactory.GetRepository<IMemberRepository>(context); var member = mRepo.GetMember(faceBookEmailAddress); if (member == null) { bool created = false; int memberId = 0; try { var uploadedFileName = this.UploadFile(string.Format(MiscHelpers.FaceBookConstants.FacebookProfilePictureUrlPattern, facebookId), MiscHelpers.ImageSize.MemberAvatar, Member.AvatarFolder); var memberData = new MemberMainData { Avatar = uploadedFileName, Facebook = faceBookLink,//string.Format(MiscHelpers.FaceBookConstants.FacebookProfileViewPattern, facebookId, facebookId), FirstName = faceBookFirstName, LastName = faceBookLastName, BirthDate = facebookBirthday }; created = _MembershipService.TryCreateAccount(faceBookEmailAddress, memberData, out memberId); } catch (Exception ex) { _Logger.Error(ex.Message); } if (created) { context = ModelFactory.GetUnitOfWork(); mRepo = ModelFactory.GetRepository<IMemberRepository>(context); member = mRepo.Get(memberId); var urlHelper = new UrlHelper(ControllerContext.RequestContext); // Send mail try { var facebookMailContent = string.Format(Worki.Resources.Email.FacebookRegistration.Content, urlHelper.ActionAbsolute(MVC.Dashboard.Profil.Edit()), member.Email, _MembershipService.GetPassword(member.Email, null)); var facebookMail = _EmailService.PrepareMessageFromDefault(new MailAddress(member.Email, member.MemberMainData.FirstName), Worki.Resources.Email.Activation.ActivationSubject, WebHelper.RenderEmailToString(member.MemberMainData.FirstName, facebookMailContent)); _EmailService.Deliver(facebookMail); } catch (Exception ex) { _Logger.Error(ex.Message); } TempData[MiscHelpers.TempDataConstants.Info] = Worki.Resources.Views.Account.InscriptionString.RegisterEworky; } else { return RedirectToAction(MVC.Home.Index()); } } var userData = member.GetUserData(); _FormsService.SignIn(member.Email, userData, /*model.RememberMe*/true, ControllerContext.HttpContext.Response); if (Url.IsLocalUrl(state)) { return Redirect(state); } else { return RedirectToAction(MVC.Home.Index()); } } } return RedirectToAction(MVC.Home.Index()); }
// // GET: /Account/OAuth/ public ActionResult OAuth(string code, string state) { FacebookOAuthResult oauthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current); if (IsDebug) { oAuthClient.RedirectUri = new Uri(redirectUrlDebug); } else { oAuthClient.RedirectUri = new Uri(redirectUrl); } dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); //Generamos el usuario. Usuario usuario = new Usuario(); usuario.FacebookId = facebookId.ToString(); usuario.Nick = (string)me.name; usuario.Email = (string)me.email; usuario.FechaCreacion = DateTime.Now; usuario.IsAdmin = false; //Comprobamos si existe en la BBDD como registrado, si no lo creamos. Usuario userdb = (from u in db.Usuarios where u.FacebookId.Equals(usuario.FacebookId) select u).FirstOrDefault(); if (userdb == null) { //Es un usuario nuevo. Lo guardamos en la BBDD. db.AddToUsuarios(usuario); db.SaveChanges(); } //Logueamos al usuario. EntrepanMembershipProvider EntrepanMembership = new EntrepanMembershipProvider(); EntrepanMembership.LogInUser(usuario.FacebookId, usuario.Id, usuario.Nick, usuario.IsAdmin, false); // prevent open redirection attack by checking if the url is local. if (Url.IsLocalUrl(state)) { return Redirect(state); } else { return RedirectToAction("Index", "Home"); } } } return RedirectToAction("Index", "Home"); }
public ActionResult ConnectAccount(string code, string state) { FacebookOAuthResult oAuthResult; bool success = false; if (FacebookOAuthResult.TryParse(Request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = new Uri(GetAccountConnectUrl()) }; dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me"); using (userProfileRepository) { var userProfile = userProfileRepository.FindUserProfileByEmail(User.Identity.Name).FirstOrDefault(); if (userProfile != null && string.IsNullOrEmpty(userProfile.FacebookID)) { userProfile.FacebookID = me.id; userProfileRepository.Save(); success = true; if (Url.IsLocalUrl(state)) { return Redirect(state); } } } } } if (!success) { TempData["UserFeedback"] = "Sorry, we were not able to connect with your Facebook account. Please try again."; } return RedirectToAction("Index", "UserProfile"); }
public FacebookAuthorizationModule(FacebookClient fb, FacebookOAuthClient fbOAuthClient, IAppUserMapper userMapper) : base("/facebook") { _fb = fb; _userMapper = userMapper; Get["/login"] = _ => { string returnUrl = Request.Query.returnUrl; dynamic parameters = new ExpandoObject(); parameters.scope = ExtendedPermissions; parameters.state = Base64UrlEncode(Encoding.UTF8.GetBytes( JsonSerializer.Current.SerializeObject(new { return_url = returnUrl }))); string loginUri = fbOAuthClient.GetLoginUrl(parameters).AbsoluteUri; return Response.AsRedirect(loginUri); }; Get["/login/callback"] = _ => { FacebookOAuthResult oAuthResult; var requestUrl = Request.Url.Scheme + "://" + Request.Url.HostName + Request.Url.BasePath + Request.Url.Path + Request.Url.Query; if (fbOAuthClient.TryParseResult(requestUrl, out oAuthResult)) { if (oAuthResult.IsSuccess) { if (!string.IsNullOrWhiteSpace(oAuthResult.Code)) { string returnUrl = null; try { if (!string.IsNullOrWhiteSpace(oAuthResult.State)) { dynamic state = JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State))); if (state.ContainsKey("return_url") && !string.IsNullOrWhiteSpace(state.return_url)) returnUrl = state.return_url; } } catch (Exception ex) { // catch exception incase user puts custom state // which contains invalid json or invalid base64 url encoding return Response.AsRedirect("~/"); } try { dynamic result = fbOAuthClient.ExchangeCodeForAccessToken(oAuthResult.Code); DateTime expiresOn; User user = ProcessSuccessfulFacebookCallback(result, out expiresOn); if (user == null) return Response.AsRedirect("~/"); // todo: prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it return this.LoginAndRedirect(user.Identifier, expiresOn, returnUrl); } catch (Exception ex) { // catch incase the user entered dummy code or the code expires // or no internet access or any other errors } } return Response.AsRedirect("~/"); } return View["FacebookLoginCallbackError", oAuthResult]; } return Response.AsRedirect("~/"); }; }
/// <summary> /// Attempts to populate registration ViewModel with data from Facebook and present to user for verification. /// </summary> /// <param name="code">Code sent to Facebook to obtain access token</param> /// <param name="state">Redirect Url</param> /// <returns>Registration view pre-populated w/ data from Facebook</returns> public ActionResult NewAccount(string code, string state) { FacebookOAuthResult oAuthResult; var viewModel = new FacebookRegisterModel(); if (FacebookOAuthResult.TryParse(Request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = new Uri(GetNewAccountUrl()) }; dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me"); viewModel = MapFacebookUser(me); } } return View("FacebookRegister", viewModel); }
/// <summary> /// Awaits a respnose from Facebook OAuth API. If Facebook login is successful, create Grassroots auth cookie. /// </summary> /// <param name="code">Code sent to Facebook to obtain access token</param> /// <param name="state">Redirect Url</param> /// <returns>Redirect based on outcome of login request</returns> public ActionResult OAuth(string code, string state) { FacebookOAuthResult oAuthResult; if (FacebookOAuthResult.TryParse(Request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = new Uri(GetOAuthRedirectUrl()) }; dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me"); using (userProfileRepository) { var userProfile = userProfileRepository.GetUserProfileByFacebookID(me.id); if (userProfile == null) { TempData["UserFeedback"] = "We can't find you in our system. Please sign in or register to create your account."; return RedirectToAction("Register", "Account"); } if (!userProfile.IsActivated) { return RedirectToAction("AwaitingActivation", "Account"); } FormsAuthentication.SetAuthCookie(userProfile.Email, false); } if (Url.IsLocalUrl(state)) { return Redirect(state); } } } return RedirectToAction("Index", "UserProfile"); }
/// <summary> /// Awaits permission of facebook user and will issue authenication cookie if successful. /// </summary> /// <param name="code">Facebook authorization code</param> /// <param name="state">Redirect url</param> private void ProcessOAuth( string code, string state ) { FacebookOAuthResult oAuthResult; if ( FacebookOAuthResult.TryParse( Request.Url, out oAuthResult ) && oAuthResult.IsSuccess ) { try { // create client to read response var oAuthClient = new FacebookOAuthClient( FacebookApplication.Current ) { RedirectUri = new Uri( GetOAuthRedirectUrl() ) }; oAuthClient.AppId = PageInstance.Site.FacebookAppId; oAuthClient.AppSecret = PageInstance.Site.FacebookAppSecret; dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken( code ); string accessToken = tokenResult.access_token; FacebookClient fbClient = new FacebookClient( accessToken ); dynamic me = fbClient.Get( "me" ); string facebookId = "FACEBOOK_" + me.id.ToString(); // query for matching id in the user table UserService userService = new UserService(); var user = userService.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.GivenName == firstName || u.NickName == 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 { person = new Person(); person.GivenName = me.first_name.ToString(); person.LastName = me.last_name.ToString(); person.Email = me.email.ToString(); if (me.gender.ToString() == "male") person.Gender = Gender.Male; if (me.gender.ToString() == "female") person.Gender = Gender.Female; person.BirthDate = Convert.ToDateTime( me.birthday.ToString() ); personService.Add( person, null ); personService.Save( person, null ); } user = userService.Create( person, AuthenticationType.Facebook, 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 } // update user record noting the login datetime user.LastLoginDate = DateTime.Now; user.LastActivityDate = DateTime.Now; userService.Save( user, user.PersonId ); FormsAuthentication.SetAuthCookie( user.UserName, false ); if ( state != null ) Response.Redirect( state ); } 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. } } }
/// <summary> /// Creates a facebook session from a signed request. /// </summary> /// <param name="appSecret"> /// The app secret. /// </param> /// <param name="signedRequest"> /// The signed request. /// </param> /// <returns> /// The facebook session. /// </returns> internal static FacebookSession Create(string appSecret, string code) { FacebookOAuthClient client = new FacebookOAuthClient(FacebookApplication.Current); client.RedirectUri = new Uri(FacebookApplication.Current.CanvasUrl); dynamic response = client.ExchangeCodeForAccessToken(code); string accessToken = response.access_token; double expires = Convert.ToDouble(response.expires); var dictionary = new JsonObject { { "access_token", accessToken } }; dictionary["expires"] = DateTimeConvertor.ToUnixTime(DateTime.Now.AddSeconds(expires)); dictionary["sig"] = GenerateSessionSignature(appSecret, dictionary); return new FacebookSession(dictionary); }
public ActionResult OAuth(string code, string state, string returnUrl) { FacebookOAuthResult oauthResult; SystemConfiguration configuration = systemConfigurationService.Get(); string redirectUrl = Url.Action("oauth", "Login"); if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(); oAuthClient.AppId = configuration.FacebookAppId.ToEmptyStringIfNull(); oAuthClient.AppSecret = configuration.FacebookApiSecret; oAuthClient.RedirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) DateTimeConvertor.FromUnixTime(tokenResult.expires); FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); try { string hostName = WebHelper.GetHostName(); Site currentSite = siteService.GetSiteByHostName(hostName); // the current site may be null if the hostname is not yet assigned!!! // (the hostname don't exists in the SiteHosts table if (currentSite == null) { log.ErrorFormat("The hostname \"{0}\" is not assigned to any site. Please check the configuration!", hostName); throw new SiteNullException(string.Format("The hostname \"{0}\" is not assigned to any site. Please check the configuration!", hostName)); } User user = authenticationService.AuthenticateUser(currentSite, facebookId.ToString(), Request.UserHostAddress, true); // if the user is found, then go to the landing page or the requested page (ReturnUrl) if (user != null) { // see http://weblogs.asp.net/jgalloway/archive/2011/01/25/preventing-open-redirection-attacks-in-asp-net-mvc.aspx if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); // Check if there are at leat 1 site, in that case redirect to that site home page IList<Site> sites = siteService.GetAllSites(); log.DebugFormat("redirect to: {0}", Url.Action("Index", "Site", new { siteid = sites[0].SiteId })); if (sites.Count > 0) return RedirectToAction("Index", "Site", new { siteid = sites[0].SiteId }); // otherwise redirect to the "generic" home return RedirectToAction("Index", "Home"); } } catch (Exception ex) { log.Error("Unexpected error while logging in", ex); throw; } //InMemoryUserStore.Add(new FacebookUser //{ // AccessToken = accessToken, // Expires = expiresOn, // FacebookId = facebookId, // Name = (string)me.name, //}); //FormsAuthentication.SetAuthCookie(facebookId.ToString(), false); //// prevent open redirection attack by checking if the url is local. //if (Url.IsLocalUrl(state)) //{ // return Redirect(state); //} //else //{ // return RedirectToAction("Index", "Home"); //} } else { log.WarnFormat("LoginController.FacebookConnect - Facebook rejected authentication!"); ViewData["AuthenticationFailed"] = "Logon unsucessfull!"; return View("Index"); } } ViewData["AuthenticationFailed"] = "Logon unsucessfull!"; return View("Index"); }
public ActionResult FacebookCallback() { var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() }; FacebookOAuthResult oAuthResult; if (oauthClient.TryParseResult(Request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { if (!string.IsNullOrWhiteSpace(oAuthResult.Code)) { string returnUrl = null; try { if (!string.IsNullOrWhiteSpace(oAuthResult.State)) { dynamic state = JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State))); if (!state.ContainsKey("csrf_token") || !ValidateFacebookCsrfToken(state.csrf_token)) { // someone tried to hack the site. return RedirectToAction("Index", "Home"); } if (state.ContainsKey("return_url") && !string.IsNullOrWhiteSpace(state.return_url)) { returnUrl = Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State)); } } } catch (Exception) { // catch incase user puts his own state, // Base64UrlDecode might throw exception if the value is not properly encoded. return RedirectToAction("Index", "Home"); } try { var result = (IDictionary<string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code); ProcessSuccesfulFacebookCallback(result); // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Facebook"); } } catch (FacebookApiException) { // catch incase the user entered dummy code or the code expired. } } return Redirect("~/"); } return View("FacebookCallbackError", oAuthResult); } return Redirect("~/"); }
//[HttpPost] public ActionResult OAuth(int id, string code, string state, string returnUrl) { FacebookOAuthResult oauthResult; SystemConfiguration configuration = systemConfigurationService.Get(); string redirectUrl = Url.Action("OAuth", "Users"); User user = userService.GetUserById(id); if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult)) { if (oauthResult.IsSuccess) { var oAuthClient = new FacebookOAuthClient(); oAuthClient.AppId = configuration.FacebookAppId.ToEmptyStringIfNull(); oAuthClient.AppSecret = configuration.FacebookApiSecret; oAuthClient.RedirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + redirectUrl); dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) DateTimeConvertor.FromUnixTime(tokenResult.expires); FacebookClient fbClient = new FacebookClient(accessToken); dynamic me = fbClient.Get("me?fields=id,name"); long facebookId = Convert.ToInt64(me.id); try { user.ExternalId = facebookId.ToString(); user.ExternalProviderUri = "www.facebook.com"; //app.GetLoginUrl().Authority; user.UpdatedDate = DateTime.UtcNow; userService.SaveUser(user); //MessageModel successMessage = new MessageModel //{ // Text = string.Format("The user {0} is now associated with the selected Facebook account!", user.DisplayName), // Icon = MessageModel.MessageIcon.Info, //}; //RegisterMessage(successMessage, true); } catch (Exception ex) { log.Error("Unexpected error while logging in", ex); MessageModel authFailedMessage = new MessageModel { Text = GlobalResource("Message_GenericError"), Icon = MessageModel.MessageIcon.Alert, }; RegisterMessage(authFailedMessage, true); } } else { log.WarnFormat("LoginController.FacebookConnect - Facebook rejected authentication!"); MessageModel authFailedMessage = new MessageModel { Text = "Sorry, Facebook rejected the authentication!", Icon = MessageModel.MessageIcon.Alert, }; RegisterMessage(authFailedMessage, true); } } //ViewData["AuthenticationFailed"] = "Logon unsucessfull!"; return RedirectToAction("Details", new {id = user.UserId}); }
public ActionResult FacebookFinishLogin(string code, string state) { if (!this.Config.AuthenticationProviders.Facebook.IsDefined) { return ResultHelper.ForbiddenResult(this); } FacebookOAuthResult oauthResult = null; if (!(state == Session.SessionToken && FacebookOAuthResult.TryParse(Request.Url, out oauthResult))) { return ResultHelper.ForbiddenResult(this); } if (!oauthResult.IsSuccess) { return ResultHelper.ForbiddenResult(this); } var oAuthClient = new FacebookOAuthClient(); oAuthClient.AppId = this.Config.AuthenticationProviders.Facebook.ApiKey; oAuthClient.AppSecret = this.Config.AuthenticationProviders.Facebook.SecretKey; oAuthClient.RedirectUri = new Uri(Request.Url, Url.Action("FacebookFinishLogin", "Authentication")); //Could throw an OAuth exception if validation fails. dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code); string accessToken = tokenResult.access_token; DateTime expiresOn = DateTime.MaxValue; if (tokenResult.ContainsKey("expires")) { expiresOn = DateTimeConvertor.FromUnixTime(tokenResult.expires); } FacebookClient fbClient = new FacebookClient(accessToken); dynamic facebookUser = fbClient.Get("me?fields=id,name,first_name,last_name,about,link,birthday,timezone"); User user = _service.GetByProviderId(AuthenticationProvider.Facebook, facebookUser.id); if (user == null) { //Its a new user for the application user = SecurityHelper.CreateUser(facebookUser); user = _service.Add(user, AuthenticationProvider.Facebook, facebookUser.id); } //Log the user in Session.SetUser(user, AuthenticationProvider.Facebook); if (Session.User == null) { //user is banned or suspended return RedirectToAction("Detail", "Users", new {id=user.Id}); } return Redirect(Session.NextUrl); }
protected void Page_Load(object sender, EventArgs e) { if (IsFacebookAuthenticated) { FacebookOAuthResult authResult; bool isOAuthResult = FacebookOAuthResult.TryParse(HttpContext.Current.Request.Url, out authResult); if (!isOAuthResult || !authResult.IsSuccess) { ShowErr("Getting data from Facebook failed. Please try again after 3-5 minutes."); return; } string returnUrl = Request.QueryString["ReturnUrl"]; string callBackUrl = Settings.Url + "/CallbackFB.aspx" + (String.IsNullOrEmpty(returnUrl) ? "" : "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl)); FacebookOAuthClient oauth = new FacebookOAuthClient(GlobalObjects.FBApp); oauth.RedirectUri = new Uri(callBackUrl); IDictionary<string, object> result = (IDictionary<string, object>)oauth.ExchangeCodeForAccessToken(authResult.Code, null); string accessToken = (string)result["access_token"]; if (String.IsNullOrEmpty(accessToken)) { ShowErr("Getting data from Facebook failed. Please try again after 3-5 minutes."); return; } AppUser appUser = LoginFacebook(accessToken); if (appUser != null) { pnlFacebookLogged.Visible = true; SessionHelper.UserId = appUser.UserId; } } else if (IsFacebookError) ShowErr("You have cancelled the login request."); }