LoginAsync() private method

private LoginAsync ( Context context, MobileServiceAuthenticationProvider provider ) : Task
context Context
provider MobileServiceAuthenticationProvider
return Task
Esempio n. 1
0
        public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider)
        {
            try
            {
                var window = UIKit.UIApplication.SharedApplication.KeyWindow;
                var root = window.RootViewController;
                if(root != null)
                {
                    var current = root;
                    while(current.PresentedViewController != null)
                    {
                        current = current.PresentedViewController;
                    }


                    Settings.LoginAttempts++;

                    var user = await client.LoginAsync(current, provider);

                    Settings.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                    Settings.UserId = user?.UserId ?? string.Empty;

                    return user;
                }
            }
            catch(Exception e)
            {
                e.Data["method"] = "LoginAsync";
                Xamarin.Insights.Report(e);
            }

            return null;
        }
 private async void Login(MobileServiceAuthenticationProvider provider)
 {
     var client = new MobileServiceClient(this.uriEntry.Value, this.keyEntry.Value);
     var user = await client.LoginAsync(this, provider);
     var alert = new UIAlertView("Welcome", "Your userId is: " + user.UserId, null, "OK");
     alert.Show();
 }
        async void Login(Object sndr, EventArgs args)
        {
            var token = new JObject();
            token.Add("access_token", "5ce8a4ae9b8deba8f67ea3604551c723");
            var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(Constants.AccountUrl, Constants.AccountKey);
            await client.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token);

        }
Esempio n. 4
0
        public async void Login()
        {
            var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(Constants.AccountUrl, Constants.AccountKey);
            var user = await client.LoginAsync(MobileServiceAuthenticationProvider.Facebook);

            ViewModel.LoginSuccss(user.UserId);



        }
Esempio n. 5
0
        public async Task<AppIdentity> Authenticate(LoginProviders provider)
        {
            Models.AppIdentity result = null;
            try
            {
#if DEBUG
                if (provider == MobileKidsIdApp.Services.LoginProviders.Test)
                {
                    result = await Models.AppIdentity.GetAppIdentityAsync("test:1", "blahblahblah");
                    return result;
                }
#endif
                var client = new MobileServiceClient("https://mobilekidsidapp.azurewebsites.net");
                MobileServiceUser authnResult = null;
                switch (provider)
                {
                    case MobileKidsIdApp.Services.LoginProviders.Google:
                        authnResult = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Google);
                        break;
                    case MobileKidsIdApp.Services.LoginProviders.Microsoft:
                        authnResult = await client.LoginAsync(this, MobileServiceAuthenticationProvider.MicrosoftAccount);
                        break;
                    case MobileKidsIdApp.Services.LoginProviders.Facebook:
                        authnResult = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Facebook);
                        break;
                    default:
                        throw new ArgumentException("LoginProvider");
                }
                result = await Models.AppIdentity.GetAppIdentityAsync(authnResult.UserId, authnResult.MobileServiceAuthenticationToken);
            }
            catch
            {
                result = new Models.AppIdentity();
            }
            return result;
        }
Esempio n. 6
0
      public static async Task<string> GetAuthToken( TargetEnvironment env = TargetEnvironment.Live )
      {
         try
         {
            var mobileService = new MobileServiceClient( GetServiceUrl( env ) );
            mobileService.AlternateLoginHost = new Uri( GetServiceUrl( TargetEnvironment.Live ) );
            var user = await mobileService.LoginAsync( MobileServiceAuthenticationProvider.Google );

            return user.MobileServiceAuthenticationToken;
            //return string.Join( ",", new string[] { user.MobileServiceAuthenticationToken, user.UserId } );
         }
         catch ( Exception ex )
         {
            return null;
         }
      }
Esempio n. 7
0
        public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider)
        {
            try
            {

                Settings.LoginAttempts++;
                var user = await client.LoginAsync(Forms.Context, provider);
                Settings.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                Settings.UserId = user?.UserId ?? string.Empty;
                return user;
            }
            catch(Exception e)
            {
                e.Data["method"] = "LoginAsync";
                Xamarin.Insights.Report(e);
            }

            return null;
        }
Esempio n. 8
0
        public static void AuthenticateWithServiceProvider(MobileServiceAuthenticationProvider authenticationProvider,
                                                           Action <CallbackResponse <MobileServiceUser> > OnAuthenticationFinished)
        {
            Task.Run(() =>
            {
                Utils.RunOnWindowsUIThread(async() =>
                {
                    try
                    {
                        user = await
                               mobileServiceClient.LoginAsync(
                            (Microsoft.WindowsAzure.MobileServices.MobileServiceAuthenticationProvider)authenticationProvider);
                    }
                    catch (Exception ex)
                    {
                        if (OnAuthenticationFinished != null)
                        {
                            Utils.RunOnUnityAppThread(() =>
                            {
                                OnAuthenticationFinished(new CallbackResponse <MobileServiceUser> {
                                    Result = null, Status = CallbackStatus.Failure, Exception = ex
                                });
                            });
                        }
                        return;
                    }

                    if (OnAuthenticationFinished != null)
                    {
                        Utils.RunOnUnityAppThread(() =>
                        {
                            OnAuthenticationFinished(new CallbackResponse <MobileServiceUser> {
                                Result = new Microsoft.UnityPlugins.MobileServiceUser(user), Status = CallbackStatus.Success, Exception = null
                            });
                        });
                    }
                });
            });
        }
        private async void OnClickGoogleLoginAndRefresh(object sender, EventArgs eventArgs)
        {
            this.loginTestResult.Text = string.Empty;

            var client = new MobileServiceClient(this.uriText.Text);
            var user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Google,
                new Dictionary<string, string>()
                {
                    { "access_type", "offline" }
                });
            string authToken = user.MobileServiceAuthenticationToken;
            this.loginTestResult.Text = "Google LoginAsync succeeded. UserId: " + user.UserId;

            MobileServiceUser refreshedUser = await client.RefreshUserAsync();

            Assert.AreEqual(user.UserId, refreshedUser.UserId);
            Assert.AreNotEqual(authToken, refreshedUser.MobileServiceAuthenticationToken);

            string message = "Google LoginAsync succeeded. Google RefreshAsync succeeded. UserId: " + user.UserId;
            this.loginTestResult.Text = message;
            System.Diagnostics.Debug.WriteLine(message);
        }
        public void LoginAsync()
        {
            TestServiceFilter hijack = new TestServiceFilter();
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
                .WithFilter(hijack);

            // Send back a successful login response
            hijack.Response.Content =
                new JsonObject()
                    .Set("authenticationToken", "rhubarb")
                    .Set("user",
                        new JsonObject()
                            .Set("userId", "123456")).Stringify();
            service.LoginAsync("donkey").ContinueWith (t =>
            {
                var current = t.Result;
                Assert.IsNotNull(current);
                Assert.AreEqual("123456", current.UserId);
                Assert.AreEqual("rhubarb", current.MobileServiceAuthenticationToken);
                Assert.That (hijack.Request.Uri.ToString(), Is.StringEnding ("login"));
                string input = JsonValue.Parse(hijack.Request.Content).Get("authenticationToken").AsString();
                Assert.AreEqual("donkey", input);
                Assert.AreEqual("POST", hijack.Request.Method);
                Assert.AreSame(current, service.CurrentUser);

                // Set the Auth Token
                service.CurrentUser.MobileServiceAuthenticationToken = "Not rhubarb";
                
                // Verify that the user token is sent with each request
                service.GetTable("foo").ReadAsync("bar").ContinueWith (rt =>
                {
                    var response = rt.Result;

                    Assert.AreEqual("Not rhubarb", hijack.Request.Headers["X-ZUMO-AUTH"]);
                    
                    // Verify error cases
                    ThrowsAsync<ArgumentNullException>(() => service.LoginAsync(null));
                    ThrowsAsync<ArgumentException>(() => service.LoginAsync(""));
                    
                    // Send back a failure and ensure it throws
                    hijack.Response.Content =
                        new JsonObject().Set("error", "login failed").Stringify();
                    hijack.Response.StatusCode = 401;
                    ThrowsAsync<InvalidOperationException>(() => service.LoginAsync("donkey"));
                }).WaitOrFail (Timeout);

            }).WaitOrFail (Timeout);
        }
 private async void OnClickLogin(object sender, EventArgs eventArgs)
 {
     var client = new MobileServiceClient(this.uriText.Text);
     var user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.MicrosoftAccount);
     System.Diagnostics.Debug.WriteLine(user.UserId);
 }
        public async Task<AuthenticationResult> AuthenticateAsync(AuthNProviderType providerType,
                                                                  IAuthNProviderSettings providerSettings)
        {
            // try without sending AMS Application key for now
            _mobileSvcsClient = new 
                MobileServiceClient(providerSettings.UrlToAuthenticationProvider);

            // default to MS account if whatever passed in is a no go
            // TODO: See Azure Mobile GitHub to see how they check for invalid Enum values
            var azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;

            // see which Azure Mobile Services Authentication Provider they want to use
            switch (providerType)
            {
                case AuthNProviderType.Google:
                    azmobProvider = MobileServiceAuthenticationProvider.Google;
                    break;
                case AuthNProviderType.Facebook:
                    azmobProvider = MobileServiceAuthenticationProvider.Facebook;
                    break;
                case AuthNProviderType.Twitter:
                    azmobProvider = MobileServiceAuthenticationProvider.Twitter;
                    break;
                case AuthNProviderType.Microsoft:
                    azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;
                    break;
                default:
                    break;
            }

            try
            {
                await _mobileSvcsClient.LoginAsync(azmobProvider);

                // TODO: How do I want to use User Profile Stuff here?
                // TODO: I will doouble set stff to see how it feels to use each

                var userProfile = await LoadUserProfile();

                var authResult = new AuthenticationResult
                {
                    ProviderName = _mobileSvcsClient.ToString(),
                    IdentityString = _mobileSvcsClient.CurrentUser.UserId,
                    MobileServicesUserToken = _mobileSvcsClient.CurrentUser.MobileServiceAuthenticationToken
                };

                return authResult;
            }
            catch (InvalidOperationException iop)
            {
                // TODO: if I try to login to Twitter and click back button on WP8
                // TODO: then System.InvalidOperationException is thrown but is NOT caught in Login VM!??  Why?
                // TODO: Must the try catch be inside here in the platform-specific authprovider?
                // TODO: Seems like that is the case, so leave it?

                // TODO: Do something useful
                //user cancelled so try again
                //MessageBox.Show("You must login to access the application.", "Please try again", MessageBoxButton.OK);
                Debug.WriteLine(
                    "AuthenticationProvider:InvalidOpException: You must login to access the application.");
            }
            catch (Exception ex)
            {
                // TODO: Do something useful
                //MessageBox.Show("We were not able to log you in, make sure you are connected to the internet and try again.", "Login failed", MessageBoxButton.OK);
                Debug.WriteLine(
                    "AuthenticationProvider:Exception: not able to log you in, make sure you are connected to the internet.");
            }
            finally
            {
                Debug.WriteLine("AuthenticationProvider:AuthenticateAsync: finally in try catch...got here!");
            }

            // TODO: how do I want to handle?
            // if I got here then something bad happened
            // TODO: Something besides null?

            return null;
        }
Esempio n. 13
0
 /// <summary>
 /// Logs in using the given login provider
 /// </summary>
 /// <param name="provider"></param>
 /// <returns>The logged in user</returns>
 public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider) =>
     await client.LoginAsync(AppDelegate.MainView, provider);
        public async Task Logout()
        {
            TestServiceFilter hijack = new TestServiceFilter();
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
                .WithFilter(hijack);

            // Send back a successful login response
            hijack.Response.Content =
                new JObject()
                    .Set("authenticationToken", "rhubarb")
                    .Set("user",
                        new JObject()
                            .Set("userId", "123456")).ToString();
            MobileServiceUser current = await service.LoginAsync("donkey");
            Assert.IsNotNull(service.CurrentUser);

            service.Logout();
            Assert.IsNull(service.CurrentUser);
        }
        public void Logout()
        {
            TestServiceFilter hijack = new TestServiceFilter();
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
                .WithFilter(hijack);

            // Send back a successful login response
            hijack.Response.Content =
                new JsonObject()
                    .Set("authenticationToken", "rhubarb")
                    .Set("user",
                        new JsonObject()
                            .Set("userId", "123456")).Stringify();

            service.LoginAsync("donkey").ContinueWith (t =>
            {
                Assert.IsNotNull(service.CurrentUser);
                
                service.Logout();
                Assert.IsNull(service.CurrentUser);
            }).WaitOrFail (Timeout);
        }
Esempio n. 16
0
 /// <summary>
 /// Logs in using the given login provider
 /// </summary>
 /// <param name="provider"></param>
 /// <returns>The logged in user</returns>
 public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider) =>
     await client.LoginAsync(Xamarin.Forms.Forms.Context, provider);
        private async void OnClickMicrosoftAccountLoginAndRefresh(object sender, EventArgs eventArgs)
        {
            this.loginTestResult.Text = string.Empty;

            var client = new MobileServiceClient(this.uriText.Text);
            var user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.MicrosoftAccount);
            string authToken = user.MobileServiceAuthenticationToken;
            this.loginTestResult.Text = "MicrosoftAccount LoginAsync succeeded. UserId: " + user.UserId;

            MobileServiceUser refreshedUser = await client.RefreshUserAsync();

            Assert.AreEqual(user.UserId, refreshedUser.UserId);
            Assert.AreNotEqual(authToken, refreshedUser.MobileServiceAuthenticationToken);

            string message = "MicrosoftAccount LoginAsync succeeded. MicrosoftAccount RefreshAsync succeeded. UserId: " + user.UserId;
            this.loginTestResult.Text = message;
            System.Diagnostics.Debug.WriteLine(message);
        }
        private async void LoginAndRefreshWithAAD()
        {
            var client = new MobileServiceClient(this.uriEntry.Value);
            MobileServiceUser user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
                new Dictionary<string, string>()
                {
                    { "response_type", "code id_token" }
                });
            string authToken = user.MobileServiceAuthenticationToken;

            MobileServiceUser refreshedUser = await client.RefreshUserAsync();

            Assert.AreEqual(user.UserId, refreshedUser.UserId);
            Assert.AreNotEqual(authToken, refreshedUser.MobileServiceAuthenticationToken);

            var alert = new UIAlertView("Welcome", "AAD Login and Refresh User succeeded. Your userId is: " + user.UserId, null, "OK");
            alert.Show();
        }
        private async void LoginAndRefreshWithMicrosoftAccount()
        {
            var client = new MobileServiceClient(this.uriEntry.Value);
            MobileServiceUser user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.MicrosoftAccount);
            string authToken = user.MobileServiceAuthenticationToken;

            MobileServiceUser refreshedUser = await client.RefreshUserAsync();

            Assert.AreEqual(user.UserId, refreshedUser.UserId);
            Assert.AreNotEqual(authToken, refreshedUser.MobileServiceAuthenticationToken);

            var alert = new UIAlertView("Welcome", "Microsoft Account Login and Refresh User succeeded. Your userId is: " + user.UserId, null, "OK");
            alert.Show();
        }
        private async void LoginAndRefreshWithGoogle()
        {
            var client = new MobileServiceClient(this.uriEntry.Value);
            MobileServiceUser user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Google,
                new Dictionary<string, string>()
                {
                    { "access_type", "offline" }
                });
            string authToken = user.MobileServiceAuthenticationToken;

            MobileServiceUser refreshedUser = await client.RefreshUserAsync();

            Assert.AreEqual(user.UserId, refreshedUser.UserId);
            Assert.AreNotEqual(authToken, refreshedUser.MobileServiceAuthenticationToken);

            var alert = new UIAlertView("Welcome", "Google Login and Refresh User succeeded. Your userId is: " + user.UserId, null, "OK");
            alert.Show();
        }
        private async void OnClickTwitterLoginAndRefresh(object sender, EventArgs eventArgs)
        {
            var client = new MobileServiceClient(this.uriText.Text);
            var user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Twitter);

            try
            {
                await client.RefreshUserAsync();
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                Assert.IsNotNull(ex.InnerException);
                Assert.AreEqual(HttpStatusCode.BadRequest, ex.Response.StatusCode);
                Assert.AreEqual(RefreshUser400ErrorMessage, ex.Message);
                string message = "Twitter LoginAsync succeeded. RefreshAsync is not supported by Twitter. UserId: " + user.UserId;
                this.loginTestResult.Text = message;
                System.Diagnostics.Debug.WriteLine(message);
                return;
            }

            Assert.Fail("RefreshAsync() should throw 400 error on Twitter account.");
        }
        public async Task<AuthNResult> AuthenticateAsync(AuthNProviderType authenticationProviderType,
                                                         IAuthNProviderSettings authenticationProviderSettings)
        {
            // try without sending Azure Mobile Service Application key for now
            //_mobileSvcsClient = new
            //    MobileServiceClient(authenticationProviderSettings.UrlToAuthenticationProvider);


            try
            {
                CurrentPlatform.Init();
                // Create the Mobile Service Client instance, using the provided
                // Mobile Service URL and key
                _mobileSvcsClient = new MobileServiceClient(authenticationProviderSettings.UrlToAuthenticationProvider);

            }
            catch (Java.Net.MalformedURLException)
            {
                //CreateAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
            }
            catch (Exception e)
            {
                //CreateAndShowDialog(e, "Error");
            }



            // default to MS account if whatever passed in is a no go
            // TODO: See Azure Mobile GitHub to see how they check for invalid Enum values
            var azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;

            // see which Azure Mobile Services Authentication Provider they want to use
            switch (authenticationProviderType)
            {
                case AuthNProviderType.Google:
                    azmobProvider = MobileServiceAuthenticationProvider.Google;
                    break;
                case AuthNProviderType.Facebook:
                    azmobProvider = MobileServiceAuthenticationProvider.Facebook;
                    break;
                case AuthNProviderType.Twitter:
                    azmobProvider = MobileServiceAuthenticationProvider.Twitter;
                    break;
                case AuthNProviderType.Microsoft:
                    azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;
                    break;
                default:
                    break;
            }

            try
            {
                // use activity hack from Michixxx to be able to call MobileServiceClient.
                // this should be the rigth way to resolve current Activity...
                var activity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity;

                await _mobileSvcsClient.LoginAsync(activity, azmobProvider);

                // TODO: How do I want to use User Profile Stuff here?
                // TODO: I will double set stuff to see how it feels to use each

                var userProfile = await LoadUserProfile();

                var authNResult = new AuthNResult
                {
                    ProviderType = authenticationProviderType.ToString(),
                    IdentityString = _mobileSvcsClient.CurrentUser.UserId,
                    MobileServicesUserToken = _mobileSvcsClient.CurrentUser.MobileServiceAuthenticationToken
                };

                return authNResult;
            }
            catch (InvalidOperationException iop)
            {
                // TODO: if I try to login to Twitter and click back button on WP8
                // TODO: then System.InvalidOperationException is thrown but is NOT caught in Login ViewModel!??  Why?
                // TODO: Must the try/catch be inside here in the platform-specific authprovider?
                // TODO: Seems like that is the case, so leave it?

                // TODO: Do something useful
                //user cancelled so try again
                //MessageBox.Show("You must login to access the application.", "Please try again", MessageBoxButton.OK);

                Console.WriteLine(
                    "AuthenticationProvider:InvalidOpException: You must login to access the application.");
                //Debug.WriteLine(
                //    "AuthenticationProvider:InvalidOpException: You must login to access the application.");
            }
            catch (Exception ex)
            {
                // TODO: Do something useful
                //MessageBox.Show("We were not able to log you in, make sure you are connected to the internet and try again.", "Login failed", MessageBoxButton.OK);
                Console.WriteLine(
                    "AuthenticationProvider:Exception: not able to log you in, make sure you are connected to the internet.");
            }
            finally
            {
                Console.WriteLine("AuthenticationProvider:AuthenticateAsync: finally - in try/catch...got here!");
            }

            // TODO: how do I want to handle?
            // if I got here, then something bad happened
            // TODO: Something besides null?

            return null;
        }
        public async Task LoginAsync()
        {
            TestServiceFilter hijack = new TestServiceFilter();
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...")
                .WithFilter(hijack);

            // Send back a successful login response
            hijack.Response.Content =
                new JObject()
                    .Set("authenticationToken", "rhubarb")
                    .Set("user",
                        new JObject()
                            .Set("userId", "123456")).ToString();
            MobileServiceUser current = await service.LoginAsync("donkey");
                
            Assert.IsNotNull(current);
            Assert.AreEqual("123456", current.UserId);
            Assert.EndsWith(hijack.Request.Uri.ToString(), "login");
            string input = JToken.Parse(hijack.Request.Content).Get("authenticationToken").AsString();
            Assert.AreEqual("donkey", input);
            Assert.AreEqual("POST", hijack.Request.Method);
            Assert.AreSame(current, service.CurrentUser);

            // Verify that the user token is sent with each request
            JToken response = await service.GetTable("foo").ReadAsync("bar");
            Assert.AreEqual("rhubarb", hijack.Request.Headers["X-ZUMO-AUTH"]);
                
            // Verify error cases
            ThrowsAsync<ArgumentNullException>(async () => await service.LoginAsync(null));
            ThrowsAsync<ArgumentException>(async () => await service.LoginAsync(""));

            // Send back a failure and ensure it throws
            hijack.Response.Content =
                new JObject().Set("error", "login failed").ToString();
            hijack.Response.StatusCode = 401;
            ThrowsAsync<InvalidOperationException>(async () =>
            {
                current = await service.LoginAsync("donkey");
            });
        }
Esempio n. 24
0
 /// <summary>
 /// Logs in using the given login provider
 /// </summary>
 /// <param name="provider"></param>
 /// <returns>The logged in user</returns>
 public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider) =>
     await client.LoginAsync(provider);