An authenticated Mobile Services user.
        /// <summary>
        /// Log a user into a Mobile Services application given an access
        /// token.
        /// </summary>
        /// <param name="authenticationToken">
        /// OAuth access token that authenticates the user.
        /// </param>
        /// <returns>
        /// Task that will complete when the user has finished authentication.
        /// </returns>
        internal Task <MobileServiceUser> SendLoginAsync(string authenticationToken)
        {
            if (authenticationToken == null)
            {
                throw new ArgumentNullException("authenticationToken");
            }
            else if (string.IsNullOrEmpty(authenticationToken))
            {
                throw new ArgumentException(
                          string.Format(
                              CultureInfo.InvariantCulture,
                              Resources.EmptyArgumentExceptionMessage,
                              "authenticationToken"));
            }

            // TODO: Decide what we should do when CurrentUser isn't null
            // (i.e., do we just log out the current user or should we throw
            // an exception?).  For now we just overwrite the the current user
            // and their token on a successful login.

            JsonObject request = new JsonObject()
                                 .Set(LoginAsyncAuthenticationTokenKey, authenticationToken);

            return(this.RequestAsync("POST", LoginAsyncUriFragment, request)
                   .ContinueWith(t =>
            {
                // Get the Mobile Services auth token and user data
                this.currentUserAuthenticationToken = t.Result.Get(LoginAsyncAuthenticationTokenKey).AsString();
                this.CurrentUser = new MobileServiceUser(t.Result.Get("user").Get("userId").AsString());

                return this.CurrentUser;
            }));
        }
 public void AuthenticateUser(User user)
 {
     CurrentUser = new MobileServiceUser(user.UserId)
     {
         MobileServiceAuthenticationToken = user.AuthToken
     };
 }
        private async System.Threading.Tasks.Task Authenticate(MobileServiceAuthenticationProvider msap)
        {
            try
            {
                user = await App.MobileService.LoginAsync(msap);
            }
            catch
            {

            }
            
            //THIS NEEDS TO BE FIXED TO STORE THE USER'S CREDENTIALs.
            //while (user == null)
            //{
            //    string message;
            //    try
            //    {
            //        user = await App.MobileService.LoginAsync(msap);
            //        message =
            //            string.Format("You are now logged in - {0}", user.UserId);
            //    }
            //    catch (InvalidOperationException)
            //    {
            //        message = "You must log in. Login Required";
            //    }

            //    MessageBox.Show(message);
            //}
        }
        public async Task SyncAsync()
        {
            try
            {
                await this.MobileService.SyncContext.PushAsync();
                await jobTable.PullAsync(null, jobTable.CreateQuery());
            }
            catch (Exception e)
            {
				if (this.MobileService.CurrentUser == null) {
					try 
					{
						User = await this.MobileService.LoginAsync (App.UIContext, 
							MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);
					}
					catch(Exception ex)
					{
						Console.WriteLine("failed to authenticate: " + ex.Message);
					}
					if (this.MobileService.CurrentUser != null) {
						await this.MobileService.SyncContext.PushAsync ();
						await jobTable.PullAsync (null, jobTable.CreateQuery ());
					}
				}
            }
        }
示例#5
0
 private async Task<LiveConnectClient> ensureConnection()
 {
     if (connection != null)
     {
         return connection;
     }
     // Initialize access to the Live Connect SDK.
     LiveAuthClient LCAuth = new LiveAuthClient("https://chivalry.azure-mobile.net/");
     LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
     // Sign in to the user's Microsoft account with the required scope.
     //    
     //  This call will display the Microsoft account sign-in screen if the user 
     //  is not already signed in to their Microsoft account through Windows 8.
     // 
     //  This call will also display the consent dialog, if the user has 
     //  has not already given consent to this app to access the data described 
     //  by the scope.
     // 
     LiveLoginResult loginResult = await LCAuth.LoginAsync(new string[] { "wl.basic", "wl.emails" });
     if (loginResult.Status == LiveConnectSessionStatus.Connected)
     {
         // Create a client session to get the profile data.
         connection = new LiveConnectClient(LCAuth.Session);
         mobileServiceUser = await App.MobileService.LoginAsync(loginResult.Session.AuthenticationToken);
         return connection;
     }
     if (LoginFailed != null)
     {
         LoginFailed(this, null);
     }
     return null;
 }
 private async System.Threading.Tasks.Task Authenticate()
 {
     // authentic user
     while (user == null)
     {
         string message;
         try
         {
             user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
             string UserId = user.UserId;
             //
             message = string.Format("You are now logged in - {0}", user.UserId);
             //Dont display unless testing!
             //MessageBox.Show(message);
             //use isolated storage/protectedclass to save useridtoken
             var result = await App.MobileService.InvokeApiAsync("facebookname", HttpMethod.Get, null);
             string json = result.ToString();
             //parse the json
             dynamic jsonParse = JObject.Parse(json);
             string UserName = result["name"].ToString();
             //export data for testing purposes.
             //facebookdata.Text = "Name = " + UserName;
             IsolatedStorageSettings.ApplicationSettings["UserID"] = UserId;
             IsolatedStorageSettings.ApplicationSettings["UserName"] = UserName;
         }
         catch (InvalidOperationException)
         {
             message = "You must log in. Login Required";
             MessageBox.Show(message);
         }
     }
     NavigationService.Navigate(new Uri("/ThemeParks.xaml", UriKind.Relative));
 }
		public async Task<bool> LogoutAsync()
		{
			bool success = false;
			try
			{
				if (user != null)
				{
					foreach (var cookie in NSHttpCookieStorage.SharedStorage.Cookies)
					{
						NSHttpCookieStorage.SharedStorage.DeleteCookie(cookie);
					}

					await TodoItemManager.DefaultManager.CurrentClient.LogoutAsync();
					var logoutAlert = new UIAlertView("Authentication", "You are now logged out " + user.UserId, null, "OK", null);
					logoutAlert.Show();
				}
				user = null;
				success = true;
			}
			catch (Exception ex)
			{
				var logoutAlert = new UIAlertView("Logout failed", ex.Message, null, "OK", null);
				logoutAlert.Show();
			}
			return success;
		}
示例#8
0
文件: AuthView.cs 项目: aocsa/CInca
        private async Task Authenticate(MobileServiceAuthenticationProvider provider)
        {
           

                try
                {
                    WAMSRepositoryService service = Mvx.Resolve<IRepositoryService>() as WAMSRepositoryService;
                    user = await service.MobileService
                        .LoginAsync(this, provider);


                }
                catch (InvalidOperationException e)
                {

                }


                var vm = ViewModel as AuthViewModel;

                if (user != null)
                {

                    vm.CreateUserCommand.Execute(user);
                }
                else
                {
                    vm.BackCommand.Execute(null);
                }
         
        }
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message =
                        string.Format("You are now logged in - {0}", user.UserId);
                    UserID = user.UserId;
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }


                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }


        }
        public async void AuthenticateAsync()
        {
            while (_user == null)
            {
                string message;
                try
                {
                    //_user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);
                    // Temporary just used fixed user
                    _user = new MobileServiceUser("SonsOfAnarchy");
                    message = $"You are now signed in - {_user.UserId}";
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();

                await InitLocalStoreAsync(); // offline sync
                await RefreshTodoItems();
            }
        }
        private async System.Threading.Tasks.Task Authenticate()
        {
            #region 04_01 Cache Logon
            //PasswordCredential passwordCredential = LogonCacher.GetCredential();
            //if (passwordCredential != null)
            //{
            //    App.MobileService.CurrentUser = new MobileServiceUser(passwordCredential.UserName);
            //    App.MobileService.CurrentUser.MobileServiceAuthenticationToken = passwordCredential.Password;
            //    user = App.MobileService.CurrentUser;
            //}
            #endregion 04_01 Cache Logon

            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message = string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (Exception exception)
                {
                    message = "You must log in. Login Required";
                }

                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }

            #region 04_01 Cache Logon
            LogonCacher.SaveCredential(App.MobileService.CurrentUser.UserId, App.MobileService.CurrentUser.MobileServiceAuthenticationToken); 
            #endregion 04_01 Cache Logon

        }
示例#12
0
    private async System.Threading.Tasks.Task Authenticate()
    {
      while (User == null)
      {
        string message = null;
        try
        {
          User = await App.MobileServiceClient
              .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
        }
        catch (InvalidOperationException)
        {
          message = "You must log in. Login Required";
        }

        if (!string.IsNullOrEmpty(message))
        {
          var dialog = new MessageDialog(message);
          dialog.Commands.Add(new UICommand("OK"));
          await dialog.ShowAsync();
        }
      }

      var user = new User { UserId = User.UserId };
      var userTable = App.MobileServiceClient.GetTable<User>();
      await userTable.InsertAsync(user);

      var channelOperation = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
      var userDeviceTable = App.MobileServiceClient.GetTable<UserDevice>();
      var userDevice = new UserDevice { UserId = user.id, DeviceUri = channelOperation.Uri };
      await userDeviceTable.InsertAsync(userDevice);

    }
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.Twitter);
                    //user = new MobileServiceUser("Twitter:32533776");
                    //user.MobileServiceAuthenticationToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6MH0.eyJleHAiOjEzNjIxOTcwMDEuNDk3LCJpc3MiOiJ1cm46bWljcm9zb2Z0OndpbmRvd3MtYXp1cmU6enVtbyIsInZlciI6MSwiYXVkIjoiVHdpdHRlciIsInVpZCI6IlR3aXR0ZXI6MzI1MzM3NzYiLCJ1cm46bWljcm9zb2Z0OmNyZWRlbnRpYWxzIjoiU3U5MnFWZlhYaWZjdWhkOE1DU1paZnBUTitFZmttK1NZVDhOcmJzK0FONEc0c1J6WmE1TnoxeUpoaWVYUnFZLzJuUHBQR1FHRTA1dlNzOHpTc2w4QytobWJoQWFGTGRsVTJBVUNkWVpGTGZyY2ZTV0tmUHZuaTMzK1RpTUN3R2QwMFRJdE84RVBrUkZDS2RmTjJEbUVSSGlYUWhQZzhSRnVna1NjdE01OVZyaGVFUjNlNmQ1NEwyZHh1azVyKzE3cy9JV0xVUVdTTk5HdXZDTUlPYThYMG1jSy82MDJQYlFTRFk3czJjYjFiST0ifQ.iU6jzc8Um8skzKqlj97g7YWqZL0Amy9eNFenkMRTFkU";
                    //App.MobileService.CurrentUser = user; 
                    message = string.Format("You are now logged in - {0} with Auth Token {1}", user.UserId, user.MobileServiceAuthenticationToken);

                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }
        public static bool LoginWithCookie()
        {
            PasswordCredential credential = null;

            try
            {
                // Try to get an existing credential from the vault.
                credential = vault.FindAllByResource(provider).FirstOrDefault();
            }
            catch (Exception)
            {
                // When there is no matching resource an error occurs, which we ignore.
            }

            if (credential != null)
            {
                // Create a user from the stored credentials.
                user = new MobileServiceUser(credential.UserName);
                credential.RetrievePassword();
                user.MobileServiceAuthenticationToken = credential.Password;

                // Set the user from the stored credentials.
                App.MobileService.CurrentUser = user;

                // Consider adding a check to determine if the token is 
                // expired, as shown in this post: http://aka.ms/jww5vp.

                return true;
            }

            return false;
        }
        private async Task AuthenticateAsync()
        {
            Microsoft.WindowsAzure.MobileServices.MobileServiceUser user = null;

            while (user == null)
            {
                string message;

                try
                {
                    user = await App.MobileService.LoginAsync("sinaweibo");

                    message = string.Format("You are now logged in - {0}", user.UserId + user.MobileServiceAuthenticationToken);
                }

                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    var dialog = new MessageDialog(message);

                    dialog.Commands.Add(new UICommand("OK"));

                    dialog.ShowAsync();
                });
            }
        }
示例#16
0
        // Log the user in with specified provider (Microsoft Account or Facebook)
        private async Task AuthenticateAsync()
        {
            // Use the PasswordVault to securely store and access credentials.
            PasswordVault vault = new PasswordVault();
            PasswordCredential credential = null;

            try
            {
                // Try to get an existing credential from the vault.
                credential = vault.FindAllByResource(provider).FirstOrDefault();
            }
            catch (Exception)
            {
                // do nothing
            }

            if (credential != null)
            {
                // Create a user from the stored credentials.
                user = new MobileServiceUser(credential.UserName);
                credential.RetrievePassword();
                user.MobileServiceAuthenticationToken = credential.Password;

                // Set the user from the stored credentials.
                App.MobileService.CurrentUser = user;

                try
                {
                    // Try to return an item now to determine if the cached credential has expired.
                    await App.MobileService.GetTable<Event>().Take(1).ToListAsync();
                }
                catch (MobileServiceInvalidOperationException ex)
                {
                    if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        // Remove the credential with the expired token.
                        vault.Remove(credential);
                        credential = null;
                    }
                }
            }
            else
            {
                try
                {
                    // Login with the identity provider.
                    user = await App.MobileService.LoginAsync(provider);

                    // Create and store the user credentials.
                    credential = new PasswordCredential(provider,
                        user.UserId, user.MobileServiceAuthenticationToken);
                    vault.Add(credential);
                }
                catch (MobileServiceInvalidOperationException ex)
                {
                    Debug.WriteLine(ex.StackTrace);
                }
            }
        }
示例#17
0
        private void SetupCurrentUser(IJsonValue value)
        {
            IJsonValue response = value;

            // Get the Mobile Services auth token and user data
            CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString());
            CurrentUser.MobileServiceAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString();
        }
示例#18
0
 public LoginToken(MobileServiceUser user, MobileServiceAuthenticationProvider provider)
 {
     if (user != null && !string.IsNullOrWhiteSpace(user.MobileServiceAuthenticationToken))
     {
         User = user;
     }
     Provider = provider;
 }
示例#19
0
        public static void CacheAuthToken(MobileServiceUser user)
        {
            var account = new Account(user.UserId);
            account.Properties.Add(TokenKeyName, user.MobileServiceAuthenticationToken);
            GetAccountStore().Save(account, App.AppName);

            Debug.WriteLine($"Cached auth token: {user.MobileServiceAuthenticationToken}");
        }
示例#20
0
 /// <summary>
 /// Makes an HTTP request that includes the standard Mobile Services
 /// headers. It will use an HttpClient with user-defined http handlers.
 /// </summary>
 /// <param name="method">
 /// The HTTP method used to request the resource.
 /// </param>
 /// <param name="uriPathAndQuery">
 /// The URI of the resource to request (relative to the Mobile Services
 /// runtime).
 /// </param>
 /// <param name="user">
 /// The object representing the user on behalf of whom the request will be sent.
 /// </param>
 /// <param name="content">
 /// Optional content to send to the resource.
 /// </param>
 /// <param name="ensureResponseContent">
 /// Optional parameter to indicate if the response should include content.
 /// </param>
 /// <param name="requestHeaders">
 /// Additional request headers to include with the request.
 /// </param>
 /// <returns>
 /// The response.
 /// </returns>
 public Task <MobileServiceHttpResponse> RequestAsync(HttpMethod method,
                                                      string uriPathAndQuery,
                                                      MobileServiceUser user,
                                                      string content             = null,
                                                      bool ensureResponseContent = true,
                                                      IDictionary <string, string> requestHeaders = null)
 {
     return(this.RequestAsync(true, method, uriPathAndQuery, user, content, ensureResponseContent, requestHeaders));
 }
        public void CreateUser()
        {
            string id = "qwrdsjjjd8";
            MobileServiceUser user = new MobileServiceUser(id);
            Assert.AreEqual(id, user.UserId);

            new MobileServiceUser(null);
            new MobileServiceUser("");
        }
示例#22
0
		private async System.Threading.Tasks.Task AuthenticateAsync(String provider) {
			string message;

			// Use the PasswordVault to securely store and access credentials.
			PasswordVault vault = new PasswordVault();
			PasswordCredential credential = null;

			while (credential == null) {
				try {
					// Try to get an existing credential from the vault.
					credential = vault.FindAllByResource(provider).FirstOrDefault();
				} catch (Exception) {
					// When there is no matching resource an error occurs, which we ignore.
				}

				if (credential != null) {
					// Create a user from the stored credentials.
					_user = new MobileServiceUser(credential.UserName);
					credential.RetrievePassword();
					_user.MobileServiceAuthenticationToken = credential.Password;

					// Set the user from the stored credentials.
					App.MobileService.CurrentUser = _user;

					try {
						// Try to return an item now to determine if the cached credential has expired.
						await App.MobileService.GetTable<TrainingItem>().Take(1).ToListAsync();
					} catch (MobileServiceInvalidOperationException ex) {
						if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) {
							// Remove the credential with the expired token.
							vault.Remove(credential);
							credential = null;
							continue;
						}
					}
				} else {
					try {
						// Login with the identity provider.
						_user = await App.MobileService.LoginAsync(provider);

						// Create and store the user credentials.
						credential = new PasswordCredential(provider, _user.UserId, _user.MobileServiceAuthenticationToken);
						vault.Add(credential);
					} catch (MobileServiceInvalidOperationException ex) {
						message = "You must log in. Login Required";
					}
				}

				message = string.Format("You are now logged in - {0}", _user.UserId);
				var dialog = new MessageDialog(message);
				dialog.Commands.Add(new UICommand("OK"));
				await dialog.ShowAsync();
			}
		}
示例#23
0
 private async Task Authenticate(UIViewController view)
 {
     try
     {
         user = await client.LoginAsync(view, MobileServiceAuthenticationProvider.MicrosoftAccount);
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine (@"ERROR - AUTHENTICATION FAILED {0}", ex.Message);
     }
 }
        /// <summary>
        /// Registers for push notifications.
        /// </summary>

        public async static Task UploadChannel(MobileServiceUser user)
        {
            channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
            await App.mobileClient.GetPush().RegisterNativeAsync(channel.Uri , new string[] { user.UserId });

            if (channel != null)
            {
                channel.PushNotificationReceived += OnPushNotificationReceived;
            }
        }
示例#25
0
        /// <summary>
        /// Makes an HTTP request that includes the standard Mobile Services
        /// headers. It will use an HttpClient that optionally has user-defined
        /// http handlers.
        /// </summary>
        /// <param name="UseHandlers">Determines if the HttpClient will use user-defined http handlers</param>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Optional content to send to the resource.
        /// </param>
        /// <param name="ensureResponseContent">
        /// Optional parameter to indicate if the response should include content.
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe</param>
        /// <returns>
        /// The content of the response as a string.
        /// </returns>
        private async Task <MobileServiceHttpResponse> RequestAsync(bool UseHandlers,
                                                                    HttpMethod method,
                                                                    string uriPathAndQuery,
                                                                    MobileServiceUser user,
                                                                    string content             = null,
                                                                    bool ensureResponseContent = true,
                                                                    IDictionary <string, string> requestHeaders = null,
                                                                    CancellationToken cancellationToken         = default(CancellationToken))
        {
            Debug.Assert(method != null);
            Debug.Assert(!string.IsNullOrEmpty(uriPathAndQuery));

            // Create the request
            HttpContent        httpContent = CreateHttpContent(content);
            HttpRequestMessage request     = this.CreateHttpRequestMessage(method, uriPathAndQuery, requestHeaders, httpContent, user);

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(RequestJsonContentType));

            // Get the response
            HttpClient client;

            if (UseHandlers)
            {
                client = this.httpClient;
            }
            else
            {
                client = this.httpClientSansHandlers;
            }
            HttpResponseMessage response = await this.SendRequestAsync(client, request, ensureResponseContent, cancellationToken);

            string responseContent = await GetResponseContent(response);

            string etag = null;

            if (response.Headers.ETag != null)
            {
                etag = response.Headers.ETag.Tag;
            }

            LinkHeaderValue link = null;

            if (response.Headers.Contains("Link"))
            {
                link = LinkHeaderValue.Parse(response.Headers.GetValues("Link").FirstOrDefault());
            }

            // Dispose of the request and response
            request.Dispose();
            response.Dispose();

            return(new MobileServiceHttpResponse(responseContent, etag, link));
        }
示例#26
0
 /// <summary>
 /// Makes an HTTP request that includes the standard Mobile Services
 /// headers. It will use an HttpClient with user-defined http handlers.
 /// </summary>
 /// <param name="method">
 /// The HTTP method used to request the resource.
 /// </param>
 /// <param name="uriPathAndQuery">
 /// The URI of the resource to request (relative to the Mobile Services
 /// runtime).
 /// </param>
 /// <param name="user">
 /// The object representing the user on behalf of whom the request will be sent.
 /// </param>
 /// <param name="content">
 /// Optional content to send to the resource.
 /// </param>
 /// <param name="ensureResponseContent">
 /// Optional parameter to indicate if the response should include content.
 /// </param>
 /// <param name="requestHeaders">
 /// Additional request headers to include with the request.
 /// </param>
 /// <param name="features">
 /// Value indicating which features of the SDK are being used in this call. Useful for telemetry.
 /// </param>
 /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe</param>
 /// <returns>
 /// The response.
 /// </returns>
 public Task <MobileServiceHttpResponse> RequestAsync(HttpMethod method,
                                                      string uriPathAndQuery,
                                                      MobileServiceUser user,
                                                      string content             = null,
                                                      bool ensureResponseContent = true,
                                                      IDictionary <string, string> requestHeaders = null,
                                                      MobileServiceFeatures features      = MobileServiceFeatures.None,
                                                      CancellationToken cancellationToken = default(CancellationToken))
 {
     requestHeaders = FeaturesHelper.AddFeaturesHeader(requestHeaders, features);
     return(this.RequestAsync(true, method, uriPathAndQuery, user, content, ensureResponseContent, requestHeaders, cancellationToken));
 }
		/// <summary>
		/// NOT PART OF INTERFACE INTO PCL
		/// </summary>
		public async Task<bool> Authenticate (Activity view) {
			try
			{
				User = await Client.LoginAsync(view, MobileServiceAuthenticationProvider.Google);
				if (User != null) return true;
			}
			catch (Exception ex)
			{
				Console.Error.WriteLine (@"ERROR - AUTHENTICATION FAILED {0}", ex.Message);
			}
			return false;
		}
        private void ExecuteDoAfterSuccessfulLogin(MobileServiceUser user)
        {
            // move to another view
            this.loggedInUserService.LoggedInUser = user;

            // don't move on if user was null
            if (this.loggedInUserService.LoggedInUser == null) {
                return;
            }

            this.ShowViewModel<UserSelectionViewModel> ();
        }
		private async Task Authenticate()
		{
			try
			{
				_user = await _client.LoginAsync(_currentActivity.Activity, _provider.AsMobileServiceProvider());
				//CreateAndShowDialog(string.Format("you are now logged in - {0}", _user.UserId), "Logged in!");
			}
			catch (Exception ex)
			{
				CreateAndShowDialog(ex, "Authentication failed");
			}
		}
 // Define a method that performs the authentication process
 // using a Twitter sign-in. 
 private async Task<bool> AuthenticateAsync()
 {
     string message;
     bool success = false;
     // This sample uses the Facebook provider.
     var provider = "Twitter";
     // Use the PasswordVault to securely store and access credentials.
     PasswordVault vault = new PasswordVault();
     PasswordCredential credential = null;
     try
     {
         // Try to get an existing credential from the vault.
         credential = vault.FindAllByResource(provider).FirstOrDefault();
     }
     catch (Exception)
     {
         // When there is no matching resource an error occurs, which we ignore.
     }
     if (credential != null)
     {
         // Create a user from the stored credentials.
         user = new MobileServiceUser(credential.UserName);
         credential.RetrievePassword();
         user.MobileServiceAuthenticationToken = credential.Password;
         // Set the user from the stored credentials.
         App.MobileService.CurrentUser = user;
         // Consider adding a check to determine if the token is 
         // expired, as shown in this post: http://aka.ms/jww5vp.
         success = true;
         message = string.Format("Cached credentials for user - {0}", user.UserId);
     }
     else
     {
         try
         {
             // Login with the identity provider.
             user = await App.MobileService
                 .LoginAsync(provider);
             // Create and store the user credentials.
             credential = new PasswordCredential(provider,
                 user.UserId, user.MobileServiceAuthenticationToken);
             vault.Add(credential);
             success = true;
         }
         catch (MobileServiceInvalidOperationException)
         {
             message = "You must log in. Login Required";
         }
     }
     return success;
 }
示例#31
0
        public async Task <bool> SignInAsync()
        {
            bool successful = false;

            try
            {
                user = await TelemetryManager.DefaultManager.CurrentClient.LoginAsync(Microsoft.WindowsAzure.MobileServices.MobileServiceAuthenticationProvider.MicrosoftAccount);

                successful = user != null;
            }
            catch { }

            return(successful);
        }
        public async Task<bool> AuthenticateAsync()
        {
            this.CurrentUserId = null;

            PasswordCredential credential;

            if (TryGetCachedCredential(out credential))
            {
                var user = new MobileServiceUser(credential.UserName);
                credential.RetrievePassword();
                user.MobileServiceAuthenticationToken = credential.Password;

                this.serviceClient.CurrentUser = user;

                if (await HasTokenExpired())
                {
                    vault.Remove(credential);
                }
                else
                {
                    this.CurrentUserId = user.UserId;
                    this.IsAuthenticated = true;
                }
            }

            if (!this.IsAuthenticated)
            {
                try
                {
                    var user = await this.serviceClient
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

                    credential = new PasswordCredential(
                        MobileServiceAuthenticationProvider.MicrosoftAccount.ToString(),
                        user.UserId,
                        user.MobileServiceAuthenticationToken);
                    vault.Add(credential);

                    this.CurrentUserId = user.UserId;
                    this.IsAuthenticated = true;
                }
                catch (MobileServiceInvalidOperationException)
                {
                    this.IsAuthenticated = false;
                }
            }

            return this.IsAuthenticated;
        }
示例#33
0
        public static async Task<bool> TryAuthenticateSilently(bool useCachedCredentials = true)
        {
            MobileServiceUser user = null;

            var vault = new PasswordVault();

            PasswordCredential savedCredentials = null;

            if (useCachedCredentials && LegacyUserId.Value != null)
            {
                try
                {
                    savedCredentials = vault.FindAllByResource(ProviderId).FirstOrDefault();
                }
                catch (Exception)
                {
                    // No credentials found.
                }
            }

            if (savedCredentials != null)
            {
                user = new MobileServiceUser(savedCredentials.UserName)
                {
                    MobileServiceAuthenticationToken = vault.Retrieve(ProviderId, savedCredentials.UserName).Password
                };

                MobileService.Client.CurrentUser = user;
            }

            if (user == null)
            {
                try
                {
                    user = await DoLoginAsync(CredentialPromptType.DoNotPrompt);
                }
                catch (Exception)
                {
                    // Do nothing
                }

                if (user != null)
                {
                    vault.Add(new PasswordCredential(ProviderId, user.UserId, user.MobileServiceAuthenticationToken));
                }
            }

            return user != null;
        }
示例#34
0
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Activity_To_Do);
            Microsoft.WindowsAzure.MobileServices.MobileServiceUser
                progressBar = FindViewById <ProgressBar> (Resource.Id.loadingProgressBar);

            // Initialize the progress bar
            progressBar.Visibility = ViewStates.Gone;

            // Create ProgressFilter to handle busy state
            var progressHandler = new ProgressHandler();

            progressHandler.BusyStateChange += (busy) => {
                if (progressBar != null)
                {
                    progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
                }
            };

            try {
                CurrentPlatform.Init();

                // Create the Mobile Service Client instance, using the provided
                // Mobile Service URL and key
                client = new MobileServiceClient(
                    applicationURL,
                    applicationKey, progressHandler);

                // Get the Mobile Service Table instance to use
                toDoTable = client.GetTable <ToDoItem> ();

                textNewToDo = FindViewById <EditText> (Resource.Id.textNewToDo);

                // Create an adapter to bind the items with the view
                adapter = new ToDoItemAdapter(this, Resource.Layout.Row_List_To_Do);
                var listViewToDo = FindViewById <ListView> (Resource.Id.listViewToDo);
                listViewToDo.Adapter = adapter;

                // Load the items from the Mobile Service
                await RefreshItemsFromTableAsync();
            } 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");
            }
        }
示例#35
0
 public void LoginHandler(object sender, EventArgs e)
 {
     TaskManager.MobileService.LoginAsync(this, MobileServiceAuthenticationProvider.Twitter).ContinueWith(t =>
                                                                                                          {
         BeginInvokeOnMainThread (() =>
                                  {
             user = t.Result;
             var alert = new UIAlertView("Welcome!",
                                         "You are now logged in and your user id is "
                                         + user.UserId, null, "OK");
             TaskManager.MobileService.CurrentUser = user;
             alert.Show ();
         });
     });
 }
示例#36
0
        /// <summary>
        /// Makes an HTTP request that includes the standard Mobile Services
        /// headers. It will use an HttpClient with user-defined http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Content to send to the resource.
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="features">
        /// Value indicating which features of the SDK are being used in this call. Useful for telemetry.
        /// </param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe</param>
        /// <returns>
        /// An <see cref="HttpResponseMessage"/>.
        /// </returns>
        public async Task <HttpResponseMessage> RequestAsync(HttpMethod method,
                                                             string uriPathAndQuery,
                                                             MobileServiceUser user,
                                                             HttpContent content,
                                                             IDictionary <string, string> requestHeaders,
                                                             MobileServiceFeatures features      = MobileServiceFeatures.None,
                                                             CancellationToken cancellationToken = default)
        {
            Arguments.IsNotNull(method, nameof(method));
            Arguments.IsNotNull(uriPathAndQuery, nameof(uriPathAndQuery));

            requestHeaders = FeaturesHelper.AddFeaturesHeader(requestHeaders, features);
            HttpRequestMessage request = this.CreateHttpRequestMessage(method, uriPathAndQuery, requestHeaders, content, user);

            return(await SendRequestAsync(httpClient, request, ensureResponseContent : false, cancellationToken : cancellationToken));
        }
        public static async Task<bool> LoginAsync()
        {
            try
            {
                user = await App.MobileService.LoginAsync(provider);

                // Create and store the user credentials.
                vault.Add(new PasswordCredential(provider, user.UserId, user.MobileServiceAuthenticationToken));

                return true;
            }
            catch (Exception)
            {
            }

            return false;
        }
示例#38
0
 private async System.Threading.Tasks.Task Autenticar(MobileServiceAuthenticationProvider provider)
 {
     while (user == null)
     {
         string mensagem = string.Empty;
         try
         {
             user = await App.MobileService.LoginAsync(provider);
             mensagem = string.Format("Usuário logado em: {0}", user.UserId);
         }
         catch(InvalidOperationException ex)
         {
             mensagem = "Usuário não Logado.";
         }
         MessageBox.Show(mensagem);
     }
 }
示例#39
0
        internal async Task InitMobileService(bool showSettingsPage, bool showLoginDialog)
        {
            if (showSettingsPage) {
                var settingsView = new SettingsView(this);
                await MainPage.Navigation.PushModalAsync(settingsView);
                await settingsView.ShowDialog();
            }

            var authHandler = new AuthHandler();
            MobileService = 
                new MobileServiceClient(Settings.Current.MobileAppUrl, new LoggingHandler(true), authHandler);

            authHandler.Client = MobileService;
            AuthenticatedUser = MobileService.CurrentUser;

            await InitLocalStoreAsync(LocalDbFilename);
            InitLocalTables();

            IPlatform platform = DependencyService.Get<IPlatform>();
            DataFilesPath = await platform.GetDataFilesPath();

#if __DROID__ && PUSH
            Droid.GcmService.RegisterWithMobilePushNotifications();
#elif __IOS__ && PUSH
           iOS.AppDelegate.IsAfterLogin = true;
           await iOS.AppDelegate.RegisterWithMobilePushNotifications();
#elif __WP__ && PUSH
           ContosoMoments.WinPhone.App.AcquirePushChannel(App.Instance.MobileService);
#endif

            if (showLoginDialog) {
                await Utils.PopulateDefaultsAsync();

                await DoLoginAsync();

                Debug.WriteLine("*** DoLoginAsync complete");

                MainPage = new NavigationPage(new AlbumsListView());
            }
            else {
                // user has already chosen an authentication type, so re-authenticate
                await AuthHandler.DoLoginAsync(Settings.Current.AuthenticationType);

                MainPage = new NavigationPage(new AlbumsListView());
            }
        }
示例#40
0
        /// <summary>
        /// Makes an HTTP request that includes the standard Mobile Services
        /// headers. It will use an HttpClient with user-defined http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Content to send to the resource.
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="features">
        /// Value indicating which features of the SDK are being used in this call. Useful for telemetry.
        /// </param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe</param>
        /// <returns>
        /// An <see cref="HttpResponseMessage"/>.
        /// </returns>
        public async Task <HttpResponseMessage> RequestAsync(HttpMethod method,
                                                             string uriPathAndQuery,
                                                             MobileServiceUser user,
                                                             HttpContent content,
                                                             IDictionary <string, string> requestHeaders,
                                                             MobileServiceFeatures features      = MobileServiceFeatures.None,
                                                             CancellationToken cancellationToken = default)
        {
            Arguments.IsNotNull(method, nameof(method));
            Arguments.IsNotNull(uriPathAndQuery, nameof(uriPathAndQuery));

            var stopwatch = new Stopwatch();

            if (MobileServiceClient.LogRequestAndResponse)
            {
                Serilog.Log.Information("MobileServiceHttpClient.RequestAsync : \n ========= BEGIN REQUEST =========");
                Serilog.Log.Information("MobileServiceHttpClient.RequestAsync : URL [" + uriPathAndQuery + "]");
                Serilog.Log.Information("MobileServiceHttpClient.RequestAsync : \n =========  END REQUEST ==========");
            }

            requestHeaders = FeaturesHelper.AddFeaturesHeader(requestHeaders, features);

            HttpRequestMessage request = this.CreateHttpRequestMessage(method, uriPathAndQuery, requestHeaders, content, user);

            // Get the response
            stopwatch.Start();
            HttpResponseMessage response = await this.SendRequestAsync(httpClient, request, ensureResponseContent : false, cancellationToken : cancellationToken);

            stopwatch.Stop();
            Serilog.Log.Information($"MobileServiceHttpClient.RequestAsync : ~~~~~~ ElapsedTime [{stopwatch.ElapsedMilliseconds}] Uri[{request.RequestUri}]");

            if (MobileServiceClient.LogRequestAndResponse)
            {
                Serilog.Log.Information($"MobileServiceHttpClient.RequestAsync : \n ========= BEGIN RESPONSE =========");
                string responseContent = await GetResponseContent(response);

                var lines = responseContent.Split(new[] { '\r', '\n' });
                foreach (var line in lines)
                {
                    Serilog.Log.Verbose("MobileServiceHttpClient.RequestAsync : \t\t" + line);
                }
                Serilog.Log.Information("MobileServiceHttpClient.RequestAsync : \n =========  END RESPONSE  ========= \n");
            }

            return(response);
        }
示例#41
0
        /// <summary>
        /// Makes an HTTP request that includes the standard Mobile Services
        /// headers. It will use an HttpClient with user-defined http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Content to send to the resource.
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="features">
        /// Value indicating which features of the SDK are being used in this call. Useful for telemetry.
        /// </param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe</param>
        /// <returns>
        /// An <see cref="HttpResponseMessage"/>.
        /// </returns>
        public async Task <HttpResponseMessage> RequestAsync(HttpMethod method,
                                                             string uriPathAndQuery,
                                                             MobileServiceUser user,
                                                             HttpContent content,
                                                             IDictionary <string, string> requestHeaders,
                                                             MobileServiceFeatures features      = MobileServiceFeatures.None,
                                                             CancellationToken cancellationToken = default(CancellationToken))
        {
            Debug.Assert(method != null);
            Debug.Assert(!string.IsNullOrEmpty(uriPathAndQuery));

            requestHeaders = FeaturesHelper.AddFeaturesHeader(requestHeaders, features);
            // Create the request
            HttpRequestMessage request = this.CreateHttpRequestMessage(method, uriPathAndQuery, requestHeaders, content, user);

            // Get the response
            HttpResponseMessage response = await this.SendRequestAsync(httpClient, request, ensureResponseContent : false, cancellationToken : cancellationToken);

            return(response);
        }
示例#42
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
                            });
                        });
                    }
                });
            });
        }
示例#43
0
 public void Logout()
 {
     this.CurrentUser = null;
 }
        /// <summary>
        /// Performs a web request and includes the standard Mobile Services
        /// headers. It will use an HttpClient without any http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Optional content to send to the resource.
        /// </param>
        /// <returns>
        /// The content of the response as a string.
        /// </returns>
        public async Task <string> RequestWithoutHandlersAsync(HttpMethod method, string uriPathAndQuery, MobileServiceUser user, string content = null)
        {
            MobileServiceHttpResponse response = await this.RequestAsync(false, method, uriPathAndQuery, user, content, false);

            return(response.Content);
        }
示例#45
0
        /// <summary>
        /// Performs a web request and includes the standard Mobile Services
        /// headers. It will use an HttpClient without any http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Optional content to send to the resource.
        /// </param>
        /// <param name="features">
        /// Optional MobileServiceFeatures used for telemetry purpose.
        /// </param>>
        /// <returns>
        /// The content of the response as a string.
        /// </returns>
        public async Task <string> RequestWithoutHandlersAsync(HttpMethod method, string uriPathAndQuery, MobileServiceUser user, string content = null, MobileServiceFeatures features = MobileServiceFeatures.None)
        {
            IDictionary <string, string> requestHeaders = FeaturesHelper.AddFeaturesHeader(requestHeaders: null, features: features);
            MobileServiceHttpResponse    response       = await this.RequestAsync(false, method, uriPathAndQuery, user, content, false, requestHeaders);

            return(response.Content);
        }
示例#46
0
        /// <summary>
        /// Creates an <see cref="HttpRequestMessage"/> with all of the
        /// required Mobile Service headers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method of the request.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="content">
        /// The content of the request.
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <returns>
        /// An <see cref="HttpRequestMessage"/> with all of the
        /// required Mobile Service headers.
        /// </returns>
        private HttpRequestMessage CreateHttpRequestMessage(HttpMethod method, string uriPathAndQuery, IDictionary <string, string> requestHeaders, HttpContent content, MobileServiceUser user)
        {
            Arguments.IsNotNull(method, nameof(method));
            Arguments.IsNotNullOrEmpty(uriPathAndQuery, nameof(uriPathAndQuery));

            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri(this.applicationUri, uriPathAndQuery),
                Method     = method
            };

            if (MobileServiceClient.LogVerbose)
            {
                Serilog.Log.Verbose("MobileServiceHttpClient.CreateHttpRequestMessage : RequestUri: " + request.RequestUri);
            }

            // Add the user's headers
            if (requestHeaders != null)
            {
                foreach (KeyValuePair <string, string> header in requestHeaders)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            // Set Mobile Services authentication, application, and telemetry headers
            request.Headers.Add(RequestInstallationIdHeader, this.installationId);
            if (user != null && !string.IsNullOrEmpty(user.MobileServiceAuthenticationToken))
            {
                request.Headers.Add(RequestAuthenticationHeader, user.MobileServiceAuthenticationToken);
            }

            // Add the content
            if (content != null)
            {
                request.Content = content;
            }

            if (MobileServiceClient.LogVerbose)
            {
                foreach (var header in request.Headers)
                {
                    if (header.Value is List <string> values)
                    {
                        Serilog.Log.Verbose("MobileServiceHttpClient.CreateHttpRequestMessage : \t header[" + header.Key + "] = [" + String.Join(", ", values) + "]");
                    }
                }
            }
            return(request);
        }
 public void Logout()
 {
     this.CurrentUser = null;
     this.currentUserAuthenticationToken = null;
 }
示例#48
0
        /// <summary>
        /// Makes an HTTP request that includes the standard Mobile Services
        /// headers. It will use an HttpClient with user-defined http handlers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <param name="content">
        /// Content to send to the resource.
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <returns>
        /// An <see cref="HttpResponseMessage"/>.
        /// </returns>
        public async Task <HttpResponseMessage> RequestAsync(HttpMethod method, string uriPathAndQuery, MobileServiceUser user, HttpContent content, IDictionary <string, string> requestHeaders)
        {
            Debug.Assert(method != null);
            Debug.Assert(!string.IsNullOrEmpty(uriPathAndQuery));

            // Create the request
            HttpRequestMessage request = this.CreateHttpRequestMessage(method, uriPathAndQuery, requestHeaders, content, user);

            // Get the response
            HttpResponseMessage response = await this.SendRequestAsync(httpClient, request, ensureResponseContent : false);

            return(response);
        }
示例#49
0
        /// <summary>
        /// Creates an <see cref="HttpRequestMessage"/> with all of the
        /// required Mobile Service headers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method of the request.
        /// </param>
        /// <param name="uriPathAndQuery">
        /// The URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="requestHeaders">
        /// Additional request headers to include with the request.
        /// </param>
        /// <param name="content">
        /// The content of the request.
        /// </param>
        /// <param name="user">
        /// The object representing the user on behalf of whom the request will be sent.
        /// </param>
        /// <returns>
        /// An <see cref="HttpRequestMessage"/> with all of the
        /// required Mobile Service headers.
        /// </returns>
        private HttpRequestMessage CreateHttpRequestMessage(HttpMethod method, string uriPathAndQuery, IDictionary <string, string> requestHeaders, HttpContent content, MobileServiceUser user)
        {
            Debug.Assert(method != null);
            Debug.Assert(!string.IsNullOrEmpty(uriPathAndQuery));

            HttpRequestMessage request = new HttpRequestMessage();

            // Set the Uri and Http Method
            request.RequestUri = new Uri(this.applicationUri, uriPathAndQuery);
            request.Method     = method;

            // Add the user's headers
            if (requestHeaders != null)
            {
                foreach (KeyValuePair <string, string> header in requestHeaders)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            // Set Mobile Services authentication, application, and telemetry headers
            request.Headers.Add(RequestInstallationIdHeader, this.installationId);
            if (user != null && !string.IsNullOrEmpty(user.MobileServiceAuthenticationToken))
            {
                request.Headers.Add(RequestAuthenticationHeader, user.MobileServiceAuthenticationToken);
            }

            // Add the content
            if (content != null)
            {
                request.Content = content;
            }

            return(request);
        }
示例#50
0
 public MobileServiceUser(Microsoft.WindowsAzure.MobileServices.MobileServiceUser mobileServiceUser)
 {
     this.MobileServiceAuthenticationToken = mobileServiceUser.MobileServiceAuthenticationToken;
     this.UserId = mobileServiceUser.UserId;
 }
示例#51
0
        /// <summary>
        /// Log a user into a Mobile Services application given a provider name and optional token object.
        /// </summary>
        /// <param name="provider" type="MobileServiceAuthenticationProvider">
        /// Authentication provider to use.
        /// </param>
        /// <param name="token" type="JsonObject">
        /// Optional, provider specific object with existing OAuth token to log in with.
        /// </param>
        /// <returns>
        /// Task that will complete when the user has finished authentication.
        /// </returns>
        internal async Task<MobileServiceUser> SendLoginAsync(MobileServiceAuthenticationProvider provider, JsonObject token = null)
        {
            if (this.LoginInProgress)
            {
                throw new InvalidOperationException(Resources.MobileServiceClient_Login_In_Progress);
            }

            if (!Enum.IsDefined(typeof(MobileServiceAuthenticationProvider), provider)) 
            {
                throw new ArgumentOutOfRangeException("provider");
            }

            string providerName = provider.ToString().ToLower();

            this.LoginInProgress = true;
            try
            {
                IJsonValue response = null;
                if (token != null)
                {
                    // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token

                    response = await this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token);
                }
                else
                {
                    // Use WebAuthenicationBroker to launch server side OAuth flow using the GET endpoint

                    Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName);
                    Uri endUri = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment);

                    WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
                        WebAuthenticationOptions.None, startUri, endUri);

                    if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.Authentication_Failed, result.ResponseErrorDetail));
                    }
                    else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                    {
                        throw new InvalidOperationException(Resources.Authentication_Canceled);
                    }

                    int i = result.ResponseData.IndexOf("#token=");
                    if (i > 0)
                    {
                        response = JsonValue.Parse(Uri.UnescapeDataString(result.ResponseData.Substring(i + 7)));
                    }
                    else
                    {
                        i = result.ResponseData.IndexOf("#error=");
                        if (i > 0)
                        {
                            throw new InvalidOperationException(string.Format(
                                CultureInfo.InvariantCulture, 
                                Resources.MobileServiceClient_Login_Error_Response,
                                Uri.UnescapeDataString(result.ResponseData.Substring(i + 7))));
                        }
                        else
                        {
                            throw new InvalidOperationException(Resources.MobileServiceClient_Login_Invalid_Response_Format);
                        }
                    }
                }

                // Get the Mobile Services auth token and user data
                this.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString());
                this.CurrentUser.MobileServiceAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString();
            }
            finally
            {
                this.LoginInProgress = false;
            }

            return this.CurrentUser;
        }