public static void Authenticate(Gamedonia.CredentialsType authenticationType, Dictionary <string, object> credentials, Action <bool> callback) { IGamedoniaAuthentication authentication = null; switch (authenticationType) { case Gamedonia.CredentialsType.GAMECENTER: authentication = new GamecenterAuthentication(); break; case Gamedonia.CredentialsType.FACEBOOK: authentication = new FacebookAuthentication((string)credentials["fb_uid"], (string)credentials["fb_access_token"]); break; case Gamedonia.CredentialsType.SILENT: authentication = new SilentAuthentication(); break; default: authentication = new SessionTokenAuthentication(); break; } authentication.Authenticate(callback); }
public static void OnLogin(Session session, JObject message) { string account_id = Utility.ReadStringFromJsonObject(message, "id"); string type = Utility.ReadStringFromJsonObject(message, "type"); if (account_id == null || type == null) { Log.Warning("Wrong login request: sid={0}", session.Id); session.Close(); return; } if (type == "fb") { // Facebook 인증을 먼저 합니다. string access_token = Utility.ReadStringFromJsonObject(message, "access_token"); if (access_token == null) { Log.Warning("Wrong login request. No access token: sid={0}, account_id={1}", session.Id, account_id); session.Close(); return; } FacebookAuthentication.AuthenticationRequest request = new FacebookAuthentication.AuthenticationRequest(access_token); FacebookAuthentication.Authenticate(request, (_1, _2, _3) => { OnFacebookAuthenticated(_1, _2, _3, session, account_id, Session.EncodingScheme.kJsonEncoding); }); } else { // Guest 는 별도의 인증 없이 로그인 합니다. AccountManager.CheckAndSetLoggedInAsync(account_id, session, (_1, _2, _3) => { OnLogin_Completed(_1, _2, _3, Session.EncodingScheme.kJsonEncoding); }); } }
public void FacebookAuthentication() { _auth = new FacebookAuthentication(ClientId, Scope, this); var auth = _auth.Authenticator; var intent = auth.GetUI(this); StartActivity(intent); }
public async Task <IActionResult> AuthenticateFacebook(FacebookAuthentication facebookAuth) { var client = new FacebookClient(facebookAuth.accessToken); dynamic authenticatingUser = client.Get("me", new { fields = "first_name,last_name,email,id" }); if (authenticatingUser != null) { //if (validPayload.EmailVerified) { string email = authenticatingUser.email; string fam = authenticatingUser.last_name; string given = authenticatingUser.first_name; //string profile = authenticatingUser.Picture; var user = await _userRepository.GetUser(email); if (user == null) { user = new User() { Email = email, FirstName = given, LastName = fam, AllowEmailNotifications = true, UsesFacebookAuth = true }; //if (!string.IsNullOrEmpty(profile)) //{ // user.ProfileImageUrl = profile; //} await _userRepository.InsertUser(user); } else if (!user.UsesFacebookAuth) { user.UsesFacebookAuth = true; //if (!string.IsNullOrEmpty(profile) && string.IsNullOrEmpty(user.ProfileImageUrl)) //{ // user.ProfileImageUrl = profile; // } await _userRepository.UpdateUser(user); } Response.SendNewToken(await _authenticationService.IssueJwtToUser(user.Id)); return(Ok()); } //else { //return Forbid(); } } else { return(Forbid()); } }
public static LoggedUser Authenticate(string facebookToken, int facebookID) { FacebookAuthentication auth = new FacebookAuthentication() { facebook_id = facebookID, facebook_token = facebookToken }; return(Authenticate(auth)); }
public ActionResult Facebook(string code, string state) { if (string.IsNullOrEmpty(code)) { if (!string.IsNullOrEmpty(Request.QueryString["error"])) //User hit cancel in auth dialog { return(null); } if (state != null) { state = "&state=" + state; } return(Redirect(FacebookAuthentication.GetFaceBookAuthUrl() + state)); } //var dateAuthed = DateTime.Now; AccessToken token; try { token = FacebookAuthentication.GetFacebookAccessToken(code); } catch (FacebookException) { return(null); } var fbUser = FacebookGraph.GetPublicData(token.Token); //If the user is already registered with the DG site they'll be redirected long fbId; bool result = long.TryParse(fbUser.Id, out fbId); if (result) { var dgUser = UserService.GetUserByFacebookId(fbId); if (dgUser != null) { FormsAuthentication.SetAuthCookie(dgUser.UserName, false); if (state != null) { return(Redirect(state)); } return(RedirectToAction("ViewUser", new { userId = dgUser.UserId })); } TempData["FacebookUser"] = fbUser; } return(RedirectToAction("CreateUser", new { redirectUrl = state })); }
public async Task <dynamic> LoginFacebook(JObject requestData) { //{"user":{"userId":"Facebook:xxx"},"authenticationToken":"xxxx"} if (requestData["access_token"] != null) { var token = requestData["access_token"].Value <string>(); var facebookAuhenticator = new FacebookAuthentication(Authentication.Configuration.GetFacebookAppId(), Authentication.Configuration.GetFacebookSecret()); var credentials = await facebookAuhenticator.GetCredentialsFromAccessTokenAsync(token); var jsonWebtoken = ZumoJsonWebTokenBuilder.CreateJsonWebToken(GetExpirationInMinutes(), ZumoAudience.Facebook, credentials); return(new { user = new { userId = jsonWebtoken.Claims.UserId }, authenticationToken = jsonWebtoken.GetToken() }); } return(null); }
public async Task <ActionResult> FacebookSignInAsync(FacebookAccount account) { var auth = new FacebookAuthentication(this.Tenant); try { var result = await auth.AuthenticateAsync(account, this.RemoteUser).ConfigureAwait(false); return(await this.OnAuthenticatedAsync(result).ConfigureAwait(true)); } catch (NpgsqlException) { return(this.Json("Access is denied.")); } }
public void When_Authenticate_With_Facebook_Service_Should_Return_Success() { var expected = new Models.LoginModel() { Email = "*****@*****.**", Password = "******", Source = "Facebook" }; var service = new FacebookAuthentication(); var actual = service.Authenticate("*****@*****.**", "1234"); Assert.AreEqual(expected.Email, actual.Email); Assert.AreEqual(expected.Password, actual.Password); Assert.AreEqual(expected.Source, actual.Source); }
public async Task <ActionResult> FacebookSignInAsync(FacebookAccount account) { var auth = new FacebookAuthentication(); try { var result = await auth.AuthenticateAsync(account, this.RemoteUser); return(this.OnAuthenticated(result)); } catch (NpgsqlException) { return(this.Json("Access is denied.")); } }
public static void OnLogin2(Session session, FunMessage message) { LobbyLoginRequest request = new LobbyLoginRequest(); if (!message.TryGetExtension_lobby_login_req( out request)) { Log.Error("OnLogin2: Wrong message."); return; } string account_id = request.id; string type = request.type; if (account_id == null || type == null) { Log.Warning("Wrong login request: sid={0}", session.Id); session.Close(); return; } if (type == "fb") { // Facebook 인증을 먼저 합니다. string access_token = request.access_token; if (access_token == null) { Log.Warning("Wrong login request. No access token: sid={0}, account_id={1}", session.Id, account_id); session.Close(); return; } FacebookAuthentication.AuthenticationRequest fb_request = new FacebookAuthentication.AuthenticationRequest(access_token); FacebookAuthentication.Authenticate(fb_request, (_1, _2, _3) => { OnFacebookAuthenticated(_1, _2, _3, session, account_id, Session.EncodingScheme.kProtobufEncoding); }); } else { // Guest 는 별도의 인증 없이 로그인 합니다. AccountManager.CheckAndSetLoggedInAsync(account_id, session, (_1, _2, _3) => { OnLogin_Completed(_1, _2, _3, Session.EncodingScheme.kProtobufEncoding); }); } }
/// <summary> /// Displays an integrated browser to allow the user to log on to the /// Facebook web page. /// </summary> public bool ConnectToFacebook(bool forceLogin) { if ((!IsSessionActive() && IsDesktopApplication) || forceLogin) { DialogResult result; //Generate State GUID for preventing CSRF _stateVerification = Guid.NewGuid().ToString(); var formLogin = new FacebookAuthentication(LoginUrl, _stateVerification, this); result = formLogin.ShowDialog(); if (result == DialogResult.Cancel) { formLogin.Dispose(); return(false); } int loggedInUserId; if (int.TryParse(GetLoggedInUser(), out loggedInUserId)) { if (loggedInUserId > 0) { formLogin.Dispose(); return(true); } else { formLogin.Dispose(); return(false); } } else { formLogin.Dispose(); return(false); } } return(true); }
public void When_Call_Index_Action_Should_Return_Valid_Model() { var expected = new Models.LoginModel() { Email = "*****@*****.**", Password = "******", Source = "Facebook" }; var service = new FacebookAuthentication(); var tenantIdStrategy = new RequestParameterTenantIdentificationStrategy("tenant"); var controller = new FacebookController(service, tenantIdStrategy); var actionResult = controller.Index(); var viewResult = actionResult as ViewResult; var actual = viewResult.ViewData.Model as Models.LoginModel; Assert.AreEqual(expected.Email, actual.Email); Assert.AreEqual(expected.Password, actual.Password); Assert.AreEqual(expected.Source, actual.Source); }
/// <summary> /// Displays an integrated browser to allow the user to log on to the /// Facebook web page. /// </summary> public void ConnectToFacebook() { if (!IsSessionActive() && IsDesktopApplication) { DialogResult result; SetAuthenticationToken(); using (var formLogin = new FacebookAuthentication(LoginUrl)) { result = formLogin.ShowDialog(); } if (result == DialogResult.OK) { CreateSession(); } else { throw new Exception("Login attempt failed"); } } }
public ActionResult HandleFacebookOAuthCallback(string code, string state) { if (code.IsNullOrWhiteSpace()) { return(this.RedirectToAction(c => c.Login())); } // TODO, decrypt redirectURL var redirectURL = string.Empty; if (!string.IsNullOrWhiteSpace(state)) { redirectURL = HttpUtility.UrlDecode(state); } var facebookAccessToken = FacebookAuthentication.ExchangeCodeForAccessToken(Request, FacebookAuthenticationOptions.FromWebConfig(), code); var user = DatabaseSession.Query <UserAccount>().Where(x => x.FacebookId == facebookAccessToken.FacebookID).SingleOrDefault(); if (user == null) { user = new UserAccount(facebookAccessToken); // TODO: redirect to a welcome page to confirm info redirectURL = this.GetURL<> } user.UpdateSeen(); var tokenEntity = user.AddFacebookAccessToken(facebookAccessToken); DatabaseSession.Save(user); DatabaseSession.Flush(); var tokenID = tokenEntity.UserFacebookAccessTokenId; HttpContext.Get <IAuthenticationManager>().SignIn(tokenID.ToString(), FacebookAuthentication.AuthenticationType); if (redirectURL.IsNullOrWhiteSpace()) { redirectURL = "~"; } return(Redirect(redirectURL)); }
public static GraphListResponse <Post> GetPosts(string id, string accessToken = "") { if (accessToken == "") { accessToken = FacebookAuthentication.GetFacebookApplicationToken().Token; } GraphListResponse <Post> data = new GraphListResponse <Post>(); string rawData = GetRawJson(id, accessToken, "posts"); if (!string.IsNullOrEmpty(rawData)) { JObject rawJson = JObject.Parse(rawData); string error = (String)rawJson["error"]; if (string.IsNullOrEmpty(error)) { data = JsonConvert.DeserializeObject <GraphListResponse <Post> >(rawData); } rawJson = null; } return(data); }
private void FacebookLogin(object sender, EventArgs e) { FacebookAuthentication facebookAuth = new FacebookAuthentication(); StartActivity(facebookAuth.InitiateLogin(this)); }
public static LoggedUser Authenticate(FacebookAuthentication auth) { var response = new TinderEndpoint.RestMethods(TinderAPI.Authenticate).Post <LoggedUser>(auth); return(response); }
public static void Login( Session session, JObject message, SessionResponse.SessionResponseHandler login_handler, SessionResponse.SessionResponseHandler logout_handler) { Log.Assert(session != null); Log.Assert(message != null); Log.Assert(login_handler != null); Log.Assert(logout_handler != null); // // 로그인 요청 예제 // // 클라이언트는 다음 메시지 형태로 로그인을 요청해야 합니다. // { // // Facebook ID 또는 구글+ ID 등 고유한 ID 를 사용해야 합니다. // "account_id": "id", // "platform": "facebook" // "access_token": "account's access token" // } // 메시지 안에 필수 파라메터가 있는지 확인합니다. if (message[kAccounId] == null || message[kAccounId].Type != JTokenType.String || message[kPlatformName] == null || message[kPlatformName].Type != JTokenType.String) { Log.Error("The message does not have '{0}' or '{1}': session={2}, message={3}", kAccounId, kPlatformName, session.Id, message.ToString()); login_handler(SessionResponse.ResponseResult.FAILED, new SessionResponse(session, 400, "Missing required fields.", new JObject())); return; } string account_id = message[kAccounId].Value <string>(); string platform = message[kPlatformName].Value <string>(); if (platform == "facebook") { // Facebook 플랫폼 사용자의 경우, 올바른 사용자인지 검증합니다. if (message[kPlatformAccessToken] == null || message[kPlatformAccessToken].Type != JTokenType.String) { Log.Error("The message does not have {0}: session={1}, message={2}", kPlatformAccessToken, session.Id, message.ToString()); login_handler(SessionResponse.ResponseResult.FAILED, new SessionResponse(session, 400, "Missing required fields.", new JObject())); return; } string access_token = message[kPlatformAccessToken].Value <string>(); FacebookAuthentication.AuthenticationRequest request = new FacebookAuthentication.AuthenticationRequest(access_token); FacebookAuthentication.AuthenticationResponseHandler on_authenticated = new FacebookAuthentication.AuthenticationResponseHandler( (FacebookAuthentication.AuthenticationRequest request2, FacebookAuthentication.AuthenticationResponse response2, bool error) => { if (error) { // Facebook 서버 오류 또는 올바르지 않은 사용자인 경우 Log.Warning("Failed to authenticate Facebook account: session={0}, code={1}, message={2}", session.Id, response2.Error.Code, response2.Error.Message); login_handler(SessionResponse.ResponseResult.FAILED, new SessionResponse(session, 400, "Missing required fields.", new JObject())); return; } Log.Info("Facebook authentication succeed: session={0}, account_id={1}", session.Id, account_id); // 이 예제에서는 로그인 시도를 기록합니다. long try_count = 0; // 분산 환경이라면 CheckAndSetLoggedInGlobalAsync() 함수를 사용해주세요. AccountManager.LoginCallback on_logged_in = new AccountManager.LoginCallback((string account_id2, Session session2, bool logged_in2) => { OnLoggedIn(account_id2, session2, logged_in2, platform, try_count, login_handler, logout_handler); }); AccountManager.CheckAndSetLoggedInAsync(account_id, session, on_logged_in); }); // Facebook 인증을 요청합니다. FacebookAuthentication.Authenticate(request, on_authenticated); } else { // // 로그인 시도 // // 요청한 세션으로 로그인을 시도합니다. 이 서버의 로그인 정책은 로그인을 시도하되, // 이미 다른 곳에서 로그인한 경우, 로그아웃 후 재시도합니다. long try_count = 0; // 분산 환경이라면 CheckAndSetLoggedInGlobalAsync() 함수를 사용해주세요. AccountManager.LoginCallback on_logged_in = new AccountManager.LoginCallback((string account_id2, Session session2, bool logged_in2) => { OnLoggedIn(account_id2, session2, logged_in2, platform, try_count, login_handler, logout_handler); }); AccountManager.CheckAndSetLoggedInAsync(account_id, session, on_logged_in); } }
public ActionResult FacebookOAuthChallenge(string redirectUrl = "") { var url = FacebookAuthentication.GetAuthChallengeURL(Request, FacebookAuthenticationOptions.FromWebConfig()); return(Redirect(url)); }
public static void Authenticate(Gamedonia.CredentialsType authenticationType, Dictionary<string,object> credentials, Action<bool> callback) { IGamedoniaAuthentication authentication = null; switch (authenticationType) { case Gamedonia.CredentialsType.GAMECENTER: authentication = new GamecenterAuthentication(); break; case Gamedonia.CredentialsType.FACEBOOK: authentication = new FacebookAuthentication((string) credentials["fb_uid"], (string) credentials["fb_access_token"]); break; case Gamedonia.CredentialsType.SILENT: authentication = new SilentAuthentication(); break; default: authentication = new SessionTokenAuthentication(); break; } authentication.Authenticate(callback); }