/// <summary> /// Authenticate user as an asynchronous operation caching the authorization on client token /// </summary> /// <param name="mobileServiceClient">The mobile service client.</param> /// <param name="providerType">Type of the provider.</param> /// <returns>Task.</returns> public static async Task AuthenticateUserCachedTokenAsync(MobileServiceClient mobileServiceClient, MobileServiceAuthenticationProvider providerType = MobileServiceAuthenticationProvider.Twitter) { _currentMobileServiceClient = mobileServiceClient; // Use the PasswordVault to securely store and access credentials. PasswordVault passwordVault = new PasswordVault(); PasswordCredential passwordCredential = null; try { // Try to get an existing credential from the vault. passwordCredential = passwordVault.FindAllByResource(providerType.ToString()).FirstOrDefault(); } catch (Exception ex) { // If there is no matching resource an error occurs // This is safe to ignore. Debug.WriteLine("Credential not in vault exception: {0}", ex.Message); } // There is a password in the vault, get it from the vault, verify that it's still valid if (passwordCredential != null) { _currentMobileServiceClient.CurrentUser = await GetUserFromVault(passwordVault, passwordCredential); } // If we have a user then we are done, if not then prompt the user to login // and save the credentials in the vault while (mobileServiceClient.CurrentUser == null || mobileServiceClient.CurrentUser.UserId == null) { string message; try { // Authenticate using provided provider type. MobileServiceUser mobileServiceUser = await mobileServiceClient.LoginAsync(providerType); message = string.Format("You are now logged in - {0}", mobileServiceClient.CurrentUser.UserId); // Create the credential package to store in the password vault passwordCredential = new PasswordCredential(providerType.ToString(), mobileServiceUser.UserId, mobileServiceUser.MobileServiceAuthenticationToken); // Add the credential package to the vault passwordVault.Add(passwordCredential); } catch (InvalidOperationException ex) { message = "You must log in. Login Required" + ex.Message; } var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } }
// Define a method that performs the authentication process // using a Facebook sign-in. private async System.Threading.Tasks.Task <bool> AuthenticateAsync(MobileServiceAuthenticationProvider provider) { string message; bool success = false; // This sample uses the Facebook provider. // 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.ToString()).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } if (false)//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: https://aka.ms/jww5vp. success = true; message = string.Format("Cached credentials for user - {0}", user.UserId); } else { try { // Sign in with the identity provider. user = await App.MobileService .LoginAsync(provider, "MobileAppTestForLulixue"); // Create and store the user credentials. credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); success = true; message = string.Format("You are now signed in - {0}", user.UserId); } catch (MobileServiceInvalidOperationException) { message = "You must sign in. Sign-In Required"; } } var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); return(success); }
private async Task Authenticate(MobileServiceAuthenticationProvider provider) { while (App.MobileServicesUser == null) { string message = null; try { App.MobileServicesUser = await App.MobileService.LoginAsync(provider); App.RegisterWithMobileServices(provider.ToString()); this.Frame.Navigate(typeof(ChatPage)); } catch (InvalidOperationException ex) { ex.ToString(); message = "You must log in. LoginPage Required"; } if (message != null) { var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } } }
/// <summary> /// Starts the authentication process. /// </summary> /// <param name="provider">The provider to authenticate with.</param> public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { try { var vault = new PasswordVault(); // Login with the identity provider. var user = await AzureAppService.Current .LoginAsync(provider); // Create and store the user credentials. var credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (InvalidOperationException invalidOperationException) { if (invalidOperationException.Message .Contains("Authentication was cancelled by the user.")) { throw new AuthenticationCanceledException("Authentication canceled by user", invalidOperationException); } throw new AuthenticationException("Authentication failed", invalidOperationException); } catch (Exception e) { throw new AuthenticationException("Authentication failed", e); } }
private async void SignIn(MobileServiceAuthenticationProvider provider) { try { IsBusy = true; var properties = new Dictionary <string, string> { { "LoginProvider", provider.ToString() } }; DependencyService.Get <IMetricsManagerService>().TrackEvent("LoginPageLogin", properties, null); await App.LoginAsync(provider); } finally { #if !__ANDROID__ // Updating the main page here will cause an exception for Android // Instead, for Android and iOS, we wait for the view to send the // `OnAppearing` event and update the main page then. if (UserSettings.IsLoggedIn) { App.GoToMainPage(); } #endif IsBusy = false; } }
/// <summary> /// Starts the authentication process. /// </summary> /// <param name="provider">The provider to authenticate with.</param> public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { try { var vault = new PasswordVault(); // Login with the identity provider. var user = await AzureAppService.Current .LoginAsync(provider); // Create and store the user credentials. var credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (InvalidOperationException invalidOperationException) { if (invalidOperationException.Message .Contains("Authentication was cancelled by the user.")) { throw new AuthenticationCanceledException("Authentication canceled by user", invalidOperationException); } throw new AuthenticationException("Authentication failed", invalidOperationException); } catch (Exception e) { throw new AuthenticationException("Authentication failed", e); } }
private async Task LoginAsync_Setup(bool useProviderStringOverload) { JObject token = new JObject(); string appUrl = MobileAppUriValidator.DummyMobileApp; MobileServiceAuthenticationProvider provider = MobileServiceAuthenticationProvider.MicrosoftAccount; string expectedUri = appUrl + ".auth/login/microsoftaccount"; TestHttpHandler hijack = new TestHttpHandler(); hijack.Response = new HttpResponseMessage(HttpStatusCode.OK); MobileServiceHttpClient.DefaultHandlerFactory = () => hijack; MobileServiceClient client = new MobileServiceClient(appUrl, hijack); if (useProviderStringOverload) { await client.LoginAsync(provider.ToString(), token); } else { await client.LoginAsync(provider, token); } Assert.AreEqual(expectedUri, hijack.Request.RequestUri.OriginalString); }
public Task <MobileServiceUser> LoginAsync(MobileServiceAuthenticationProvider provider, JObject token) { if (!Enum.IsDefined(typeof(MobileServiceAuthenticationProvider), provider)) { throw new ArgumentOutOfRangeException(nameof(provider)); } return(this.LoginAsync(provider.ToString(), token)); }
public async Task <object> GetDataAsync(MobileServiceUser user, MobileServiceAuthenticationProvider provider) { var providerParameter = new Dictionary <string, string>(); providerParameter.Add("provider", provider.ToString()); FacebookUser apiResult = await _client.InvokeApiAsync <FacebookUser>("Identity", HttpMethod.Get, providerParameter); return(apiResult); }
private async void Login(MobileServiceAuthenticationProvider provider) { var client = new MobileServiceClient(this.uriEntry.Value); var user = await client.LoginAsync(this, provider); var alert = new UIAlertView("Welcome", provider.ToString() + " Login succeeded. Your userId is: " + user.UserId, null, "OK"); alert.Show(); }
/// <summary> /// Client-directed single sign on (POST with access token) /// </summary> public void Login(MobileServiceAuthenticationProvider provider, string token, Action <IRestResponse <MobileServiceUser> > callback = null) { string p = provider.ToString().ToLower(); string uri = IsAppService() ? ".auth/login/" + p : "login/" + p; ZumoRequest request = new ZumoRequest(this, uri, Method.POST); Debug.Log("Login Request Uri: " + uri + " access token: " + token); request.AddBodyAccessToken(token); this.ExecuteAsync(request, callback); }
private async void Login(MobileServiceAuthenticationProvider provider) { var client = new MobileServiceClient(this.uriEntry.Value); AppDelegate.ResumeWithURL = url => url.Scheme == uriScheme && client.ResumeWithURL(url); var user = await client.LoginAsync(this, provider, uriScheme); var alert = new UIAlertView("Welcome", provider.ToString() + " Login succeeded. Your userId is: " + user.UserId, null, "OK"); alert.Show(); }
/// <summary> /// Client-directed single sign on (POST with access token) /// </summary> public IEnumerator Login(MobileServiceAuthenticationProvider provider, string token, Action <IRestResponse <MobileServiceUser> > callback = null) { string p = provider.ToString().ToLower(); string url = string.Format("{0}/.auth/login/{1}", AppUrl, p); Debug.Log("Login Request Url: " + url + " access token: " + token); ZumoRequest request = new ZumoRequest(this, url, Method.POST); request.AddBodyAccessToken(token); yield return(request.request.Send()); request.ParseJson <MobileServiceUser> (callback); }
public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { var passwordVault = new PasswordVault(); PasswordCredential credential = null; var settings = ApplicationData.Current.RoamingSettings; try { await this.MobileService.LoginAsync(provider); credential = new PasswordCredential(provider.ToString(), this.MobileService.User.UserId, this.MobileService.User.MobileServiceAuthenticationToken); passwordVault.Add(credential); settings.Values[LastUsedProvider] = provider.ToString(); this.OnNavigate?.Invoke(Tasks, null); } catch (InvalidOperationException) { await this.OnShowErrorAsync?.Invoke("Authentication failed. Please try again."); } }
private async void OnChooseAuthProvider(MobileServiceAuthenticationProvider authenticationProviderProvider) { try { _telemetryClient.TrackEvent(TelemetryEvents.SignInInitiated, new Dictionary <string, string> { { TelemetryProperties.AuthenticationProvider, authenticationProviderProvider.ToString() } }); await _photoService.SignInAsync(authenticationProviderProvider); _telemetryClient.TrackEvent(TelemetryEvents.SignInSuccess, new Dictionary <string, string> { { TelemetryProperties.AuthenticationProvider, authenticationProviderProvider.ToString() } }); if (RedirectToProfilePage) { _navigationFacade.NavigateToProfileView(); _navigationFacade.RemoveBackStackFrames(1); } } catch (AuthenticationException) { _telemetryClient.TrackEvent(TelemetryEvents.SignInFail); await _dialogService.ShowNotification("AuthenticationFailed_Message", "AuthenticationFailed_Title"); } catch (AuthenticationCanceledException) { _telemetryClient.TrackEvent(TelemetryEvents.SignInCanceled); // User canceled, do nothing in this case. } catch (Exception) { _telemetryClient.TrackEvent(TelemetryEvents.SignInFail); await _dialogService.ShowNotification("GenericError_Title", "GenericError_Message"); } }
/// <summary> /// Tests the <see cref="MobileServiceClient.LoginAsync"/> functionality on the platform. /// </summary> /// <param name="provider">The provider with which to login. /// </param> /// <param name="useProviderStringOverload">Indicates if the call to <see cref="MobileServiceClient.LoginAsync"/> /// should be made with the overload where the provider is passed as a string. /// </param> /// <returns>The UserId and MobileServiceAuthentication token obtained from logging in.</returns> public static async Task<string> TestLoginAsync(MobileServiceAuthenticationProvider provider, bool useProviderStringOverload) { MobileServiceUser user; if (useProviderStringOverload) { user = await client.LoginAsync(provider.ToString()); } else { user = await client.LoginAsync(provider); } return string.Format("UserId: {0} Token: {1}", user.UserId, user.MobileServiceAuthenticationToken); }
/// <summary> /// Tests the <see cref="MobileServiceClient.LoginAsync"/> functionality on the platform. /// </summary> /// <param name="provider">The provider with which to login. /// </param> /// <param name="useSingleSignOn">Indicates if single sign-on should be used when logging in. /// </param> /// <param name="useProviderStringOverload">Indicates if the call to <see cref="MobileServiceClient.LoginAsync"/> /// should be made with the overload where the provider is passed as a string. /// </param> /// <returns>The UserId and MobileServiceAuthentication token obtained from logging in.</returns> public static async Task <string> TestLoginAsync(MobileServiceAuthenticationProvider provider, bool useSingleSignOn, bool useProviderStringOverload) { MobileServiceUser user; if (useProviderStringOverload) { user = await client.LoginAsync(provider.ToString(), useSingleSignOn); } else { user = await client.LoginAsync(provider, useSingleSignOn); } return(string.Format("UserId: {0} Token: {1}", user.UserId, user.MobileServiceAuthenticationToken)); }
public async static Task <MobileServiceUser> LoginAsync(this MobileServiceClient client, MobileServiceAuthenticationProvider provider) { Uri startUri = new Uri(client.ApplicationUri, "login/" + provider.ToString().ToLowerInvariant()); Uri endUri = new Uri(client.ApplicationUri, "login/done"); LoginPage loginPage = new LoginPage(startUri, endUri); string token = await loginPage.Display(); JObject tokenObj = JObject.Parse(token.Replace("%2C", ",")); var userId = tokenObj["user"]["userId"].ToObject <string>(); var authToken = tokenObj["authenticationToken"].ToObject <string>(); var result = new MobileServiceUser(userId); result.MobileServiceAuthenticationToken = authToken; client.CurrentUser = result; return(result); }
private async void SignIn(MobileServiceAuthenticationProvider provider) { var properties = new Dictionary <string, string> { { "LoginProvider", provider.ToString() } }; DependencyService.Get <IMetricsManagerService>().TrackEvent("ProfilePageLogin", properties, null); await App.LoginAsync(provider); OnPropertyChanged(nameof(IsAnonymous)); OnPropertyChanged(nameof(IsLoggedIn)); OnPropertyChanged(nameof(IsGoogleLoginAvailable)); ChangeAllProperties(); UpdateCurrentInfo(); }
/// <summary> /// Tests the <see cref="MobileServiceClient.LoginAsync"/> functionality on the platform. /// </summary> /// <param name="provider">The provider with which to login. /// </param> /// <param name="useSingleSignOn">Indicates if single sign-on should be used when logging in. /// </param> /// <param name="useProviderStringOverload">Indicates if the call to <see cref="MobileServiceClient.LoginAsync"/> /// should be made with the overload where the provider is passed as a string. /// </param> /// <returns>The UserId and MobileServiceAuthentication token obtained from logging in.</returns> public static async Task<string> TestLoginAsync(MobileServiceAuthenticationProvider provider, bool useSingleSignOn, bool useProviderStringOverload) { MobileServiceUser user; await TestCRUDAsync("Public", false, false); await TestCRUDAsync("Authorized", true, false); if (useProviderStringOverload) { user = await client.LoginAsync(provider.ToString(), useSingleSignOn); } else { user = await client.LoginAsync(provider, useSingleSignOn); } await TestCRUDAsync("Public", false, true); await TestCRUDAsync("Authorized", true, true); await TestLogoutAsync(); await TestCRUDAsync("Authorized", true, false); return string.Format("UserId: {0} Token: {1}", user.UserId, user.MobileServiceAuthenticationToken); }
/// <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="JObject"> /// 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> public void LoginWithBrowser(MobileServiceAuthenticationProvider provider, WebAuthenticationBrokerStruct broker, Action <MobileServiceUser, Exception> continueWith) { // Proper Async Tasks Programming cannot integrate with Windows Phone (stupid) Async Mechanisim which use Events... (ex: UploadStringCompleted) //var asyncTask = new Task<MobileServiceUser>(() => this.StartLoginAsync(provider, authorizationBrowser)); //asyncTask.Start(); //return asyncTask; this._broker = broker; _successContinueWith += continueWith; if (this.LoginInProgress) { throw new InvalidOperationException("Error, Login is still in progress.."); } if (!Enum.IsDefined(typeof(MobileServiceAuthenticationProvider), provider)) { throw new ArgumentOutOfRangeException("provider"); } var providerName = provider.ToString().ToLower(); this.LoginInProgress = true; try { //Launch the OAuth flow. broker.Dispacher.BeginInvoke(() => { broker.LoadingGrid.Visibility = Visibility.Visible; }); broker.AuthorizationBrowser.Navigating += this.OnAuthorizationBrowserNavigating; broker.AuthorizationBrowser.Navigated += this.OnAuthorizationBrowserNavigated; broker.AuthorizationBrowser.Navigate( new Uri(this._serviceUrl + LoginAsyncUriFragment + "/" + providerName)); } catch (Exception ex) { //on Error CompleteOAuthFlow(false, ex.Message); } }
/// <summary> /// Tests the <see cref="MobileServiceClient.LoginAsync"/> functionality on the platform. /// </summary> /// <param name="provider">The provider with which to login. /// </param> /// <param name="useSingleSignOn">Indicates if single sign-on should be used when logging in. /// </param> /// <param name="useProviderStringOverload">Indicates if the call to <see cref="MobileServiceClient.LoginAsync"/> /// should be made with the overload where the provider is passed as a string. /// </param> /// <returns>The UserId and MobileServiceAuthentication token obtained from logging in.</returns> public static async Task <string> TestLoginAsync(MobileServiceAuthenticationProvider provider, bool useSingleSignOn, bool useProviderStringOverload) { MobileServiceUser user; await TestCRUDAsync("Public", false, false); await TestCRUDAsync("Authorized", true, false); if (useProviderStringOverload) { user = await client.LoginAsync(provider.ToString(), useSingleSignOn); } else { user = await client.LoginAsync(provider, useSingleSignOn); } await TestCRUDAsync("Public", false, true); await TestCRUDAsync("Authorized", true, true); await TestLogoutAsync(); await TestCRUDAsync("Authorized", true, false); return(string.Format("UserId: {0} Token: {1}", user.UserId, user.MobileServiceAuthenticationToken)); }
//public async Task<MobileServiceUser> CustomLogin(string username, string password) //{ // string message; // MobileServiceUser user = null; // // Use the PasswordVault to securely store and access credentials. // PasswordVault vault = new PasswordVault(); // PasswordCredential credential = null; // try // { // // get the token // //var token = await GetAuthenticationToken(username, password); // //// authenticate: create and use a mobile service user // //user = new MobileServiceUser(token.Guid); // //user.MobileServiceAuthenticationToken = token.Access_Token; // //// Create and store the user credentials. // //credential = new PasswordCredential("custom", // // user.UserId, user.MobileServiceAuthenticationToken); // //vault.Add(credential); // //App.MobileService.CurrentUser = user; // } // catch (MobileServiceInvalidOperationException) // { // message = "You must log in. Login Required"; // await HelpersClass.ShowDialogAsync(message); // } // return user; //} //public async Task<AuthenticationToken> //GetAuthenticationToken(string username, string email, string password) //{ // try // { // //using (var pc = new PrincipalContext(ContextType.Domain)) // //{ // // using (var up = new UserPrincipal(pc)) // // { // // up.SamAccountName = username; // // up.EmailAddress = email; // // up.SetPassword(password); // // up.Enabled = true; // // up.ExpirePasswordNow(); // // up.Save(); // // } // //} // } // catch (MobileServiceInvalidOperationException exception) // { // //if (string.Equals(exception.Message, "invalid_grant")) // // throw new InvalidGrantException("Wrong credentails", // // exception); // //else // // throw; // } // return null; //} public async Task <MobileServiceUser> Login(MobileServiceAuthenticationProvider provider) { string message; MobileServiceUser user = null; // This sample uses the Facebook provider. // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Login with the identity provider. user = await App.MobileService .LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); JObject obj = new JObject(); obj.Add("Id", user.UserId); obj.Add("Name", credential.UserName); vault.Add(credential); string response = await CallAPI(@"/api/Users", HTTPMETHOD.POST, obj); message = string.Format("You are now logged in - {0}", user.UserId); } catch (MobileServiceInvalidOperationException) { message = "You must log in. Login Required"; await HelpersClass.ShowDialogAsync(message); } catch { } return(user); }
public async Task Authenticate(MobileServiceAuthenticationProvider provider) { while (App.MobileServicesUser == null) { string message = null; try { App.MobileServicesUser = await App.MobileService.LoginAsync(provider); App.RegisterWithMobileServices(provider.ToString()); NavigationService.Navigate(new Uri("/ChatPage.xaml", UriKind.Relative)); } catch (InvalidOperationException ex) { ex.ToString(); message = "You must log in. Login Required"; } if (message != null) { MessageBox.Show(message); } } }
/// <summary> /// Logins user using provider and stores token in acount store. /// Stored token will be used in <see cref="Authenticate"/> method. /// Sets logged user to <see cref="AuthMobileServiceClient.CurrentUser"/> and /// access to authorized requests should be gratned. /// </summary> /// <param name="provider">The provider.</param> /// <returns>Login result.</returns> public async Task <bool> Login(MobileServiceAuthenticationProvider provider) { var parameters = new Dictionary <string, string> { { "access_type", "offline" }, { "prompt", "consent" } }; await _mobileServiceClient.LoginAsync(_context, provider, _uriScheme, parameters); if (_mobileServiceClient.CurrentUser != null) { _accountStoreService.StoreTokenInSecureStore(new RefreshTokenInfo() { UserId = _mobileServiceClient.CurrentUser.UserId, Provider = provider.ToString(), RefreshToken = _mobileServiceClient.CurrentUser.MobileServiceAuthenticationToken }); return(true); } else { return(false); } }
private async Task Authenticate(MobileServiceAuthenticationProvider provider) { while (App.MobileServicesUser == null) { string message = null; try { App.MobileServicesUser = await App.MobileService.LoginAsync(provider); App.RegisterWithMobileServices(provider.ToString()); this.Frame.Navigate(typeof(ChatPage)); } catch (InvalidOperationException ex) { ex.ToString(); message = "You must log in. LoginPage Required"; } if (message != null) { var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } } }
/// <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.currentUserAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString(); this.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString()); } finally { this.LoginInProgress = false; } return this.CurrentUser; }
private async void Login(MobileServiceAuthenticationProvider provider) { var client = new MobileServiceClient(this.uriEntry.Value); var user = await client.LoginAsync(this, provider); var alert = new UIAlertView("Welcome", provider.ToString() + " Login succeeded. Your userId is: " + user.UserId, null, "OK"); alert.Show(); }
internal Task<MobileServiceUser> SendLoginAsync(RectangleF rect, object view, 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; TaskCompletionSource<MobileServiceUser> tcs = new TaskCompletionSource<MobileServiceUser> (); if (token != null) { // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token) .ContinueWith (t => { this.LoginInProgress = false; if (t.IsCanceled) tcs.SetCanceled(); else if (t.IsFaulted) tcs.SetException (t.Exception.InnerExceptions); else { SetupCurrentUser (t.Result); tcs.SetResult (this.CurrentUser); } }); } else { // Launch server side OAuth flow using the GET endpoint Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName); Uri endUri = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment); WebRedirectAuthenticator auth = new WebRedirectAuthenticator (startUri, endUri); auth.ClearCookiesBeforeLogin = false; UIViewController c = auth.GetUI(); UIViewController controller = null; UIPopoverController popover = null; auth.Error += (o, e) => { this.LoginInProgress = false; if (controller != null) controller.DismissModalViewControllerAnimated (true); if (popover != null) popover.Dismiss (true); Exception ex = e.Exception ?? new Exception (e.Message); tcs.TrySetException (ex); }; auth.Completed += (o, e) => { this.LoginInProgress = false; if (controller != null) controller.DismissModalViewControllerAnimated (true); if (popover != null) popover.Dismiss (true); if (!e.IsAuthenticated) tcs.TrySetCanceled(); else { SetupCurrentUser (JsonValue.Parse (e.Account.Properties["token"])); tcs.TrySetResult (this.CurrentUser); } }; controller = view as UIViewController; if (controller != null) { controller.PresentModalViewController (c, true); } else { UIView v = view as UIView; UIBarButtonItem barButton = view as UIBarButtonItem; popover = new UIPopoverController (c); if (barButton != null) popover.PresentFromBarButtonItem (barButton, UIPopoverArrowDirection.Any, true); else popover.PresentFromRect (rect, v, UIPopoverArrowDirection.Any, true); } } return tcs.Task; }
/// <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="client"> /// The <see cref="MobileServiceClient"/> to login with. /// </param> /// <param name="useSingleSignOn"> /// Indicates that single sign-on should be used. Single sign-on requires that the /// application's Package SID be registered with the Microsoft Azure Mobile Service, but it /// provides a better experience as HTTP cookies are supported so that users do not have to /// login in everytime the application is launched. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, MobileServiceAuthenticationProvider provider, bool useSingleSignOn) { return LoginAsync(client, provider.ToString(), useSingleSignOn); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client">The MobileServiceClient instance to login with</param> /// <param name="viewController">UIViewController used to display modal login UI on iPhone/iPods.</param> /// <param name="provider">Authentication provider to use.</param> /// <param name="uriScheme">The URL scheme of the application.</param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this MobileServiceClient client, UIViewController viewController, MobileServiceAuthenticationProvider provider, string uriScheme, IDictionary <string, string> parameters) => LoginAsync(client, default, viewController, provider.ToString(), uriScheme, parameters);
/// <summary> /// Log a user into a Mobile Services application given a provider name and optional token object. /// </summary> /// <param name="context" type="Android.Content.Context"> /// Context used to launch login UI. /// </param> /// <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 Task <MobileServiceUser> SendLoginAsync(Context context, 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; TaskCompletionSource <MobileServiceUser> tcs = new TaskCompletionSource <MobileServiceUser> (); if (token != null) { // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token) .ContinueWith(t => { this.LoginInProgress = false; if (t.IsCanceled) { tcs.SetCanceled(); } else if (t.IsFaulted) { tcs.SetException(t.Exception.InnerExceptions); } else { SetupCurrentUser(t.Result); tcs.SetResult(this.CurrentUser); } }); } else { // Launch server side OAuth flow using the GET endpoint Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName); Uri endUri = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment); WebRedirectAuthenticator auth = new WebRedirectAuthenticator(startUri, endUri); auth.ClearCookiesBeforeLogin = false; auth.Error += (o, e) => { this.LoginInProgress = false; Exception ex = e.Exception ?? new Exception(e.Message); tcs.TrySetException(ex); }; auth.Completed += (o, e) => { this.LoginInProgress = false; if (!e.IsAuthenticated) { tcs.TrySetCanceled(); } else { SetupCurrentUser(JsonValue.Parse(e.Account.Properties["token"])); tcs.TrySetResult(this.CurrentUser); } }; Intent intent = auth.GetUI(context); context.StartActivity(intent); } return(tcs.Task); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="rectangle" type="System.Drawing.RectangleF"> /// The area in <paramref name="view"/> to anchor to. /// </param> /// <param name="view" type="MonoTouch.UIKit.UIView"> /// UIView used to display a popover from on iPad. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this IMobileServiceClient client, RectangleF rectangle, UIView view, MobileServiceAuthenticationProvider provider, IDictionary <string, string> parameters) { return(LoginAsync(client, rectangle, (object)view, provider.ToString(), parameters)); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="context" type="Android.Content.Context"> /// The Context to display the Login UI in. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, Context context, MobileServiceAuthenticationProvider provider) { return LoginAsync(client, context, provider.ToString()); }
/// <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="client"> /// The <see cref="MobileServiceClient"/> to login with. /// </param> /// <param name="useSingleSignOn"> /// Indicates that single sign-on should be used. Single sign-on requires that the /// application's Package SID be registered with the Microsoft Azure Mobile Service, but it /// provides a better experience as HTTP cookies are supported so that users do not have to /// login in everytime the application is launched. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this IMobileServiceClient client, MobileServiceAuthenticationProvider provider, bool useSingleSignOn, IDictionary <string, string> parameters) { return(LoginAsync(client, provider.ToString(), useSingleSignOn, parameters)); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="rectangle" type="System.Drawing.RectangleF"> /// The area in <paramref name="view"/> to anchor to. /// </param> /// <param name="view" type="MonoTouch.UIKit.UIView"> /// UIView used to display a popover from on iPad. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, RectangleF rectangle, UIView view, MobileServiceAuthenticationProvider provider) { return LoginAsync(client, rectangle, (object)view, provider.ToString()); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="barButtonItem" type="MonoTouch.UIKit.UIBarButtonItem"> /// UIBarButtonItem used to display a popover from on iPad. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync (this IMobileServiceClient client, UIBarButtonItem barButtonItem, MobileServiceAuthenticationProvider provider) { return LoginAsync(client, default(RectangleF), barButtonItem, provider.ToString()); }
public async Task<MobileServiceUser> LoginAsync(MobileServiceAuthenticationProvider provider) { IDictionary<string, string> p = new Dictionary<string, string>(); return await ContosoMoments.App.MobileService.LoginAsync(provider.ToString(), p); }
/// <summary> /// Log a user into a Mobile Services application given a provider name and optional token object. /// </summary> /// <param name="context" type="Android.Content.Context"> /// Context used to launch login UI. /// </param> /// <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 Task<MobileServiceUser> SendLoginAsync(Context context, 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; TaskCompletionSource<MobileServiceUser> tcs = new TaskCompletionSource<MobileServiceUser> (); if (token != null) { // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token) .ContinueWith (t => { this.LoginInProgress = false; if (t.IsCanceled) tcs.SetCanceled(); else if (t.IsFaulted) tcs.SetException (t.Exception.InnerExceptions); else { SetupCurrentUser (t.Result); tcs.SetResult (this.CurrentUser); } }); } else { // Launch server side OAuth flow using the GET endpoint Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName); Uri endUri = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment); WebRedirectAuthenticator auth = new WebRedirectAuthenticator (startUri, endUri); auth.ClearCookiesBeforeLogin = false; auth.Error += (o, e) => { this.LoginInProgress = false; Exception ex = e.Exception ?? new Exception (e.Message); tcs.TrySetException (ex); }; auth.Completed += (o, e) => { this.LoginInProgress = false; if (!e.IsAuthenticated) tcs.TrySetCanceled(); else { SetupCurrentUser (JsonValue.Parse (e.Account.Properties["token"])); tcs.TrySetResult (this.CurrentUser); } }; Intent intent = auth.GetUI (context); context.StartActivity (intent); } return tcs.Task; }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="provider"> /// Authentication provider to use. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this IMobileServiceClient client, MobileServiceAuthenticationProvider provider) { return(LoginAsync(client, provider.ToString())); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="rectangle" type="System.Drawing.RectangleF"> /// The area in <paramref name="view"/> to anchor to. /// </param> /// <param name="view" type="MonoTouch.UIKit.UIView"> /// UIView used to display a popover from on iPad. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, RectangleF rectangle, UIView view, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters) { return LoginAsync(client, rectangle, (object)view, provider.ToString(), parameters); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="context" type="Android.Content.Context"> /// The Context to display the Login UI in. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this IMobileServiceClient client, Context context, MobileServiceAuthenticationProvider provider, IDictionary <string, string> parameters) { return(LoginAsync(client, context, provider.ToString(), parameters)); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="viewController" type="MonoTouch.UIKit.UIViewController"> /// UIViewController used to display modal login UI on iPhone/iPods. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, UIViewController viewController, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters) { return LoginAsync(client, default(RectangleF), viewController, provider.ToString(), parameters); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client" type="Microsoft.WindowsAzure.MobileServices.IMobileServiceClient"> /// The MobileServiceClient instance to login with /// </param> /// <param name="viewController" type="MonoTouch.UIKit.UIViewController"> /// UIViewController used to display modal login UI on iPhone/iPods. /// </param> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task <MobileServiceUser> LoginAsync(this IMobileServiceClient client, UIViewController viewController, MobileServiceAuthenticationProvider provider, IDictionary <string, string> parameters) { return(LoginAsync(client, default(RectangleF), viewController, provider.ToString(), parameters)); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="provider"> /// Authentication provider to use. /// </param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public static Task<MobileServiceUser> LoginAsync(this IMobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters) { return LoginAsync(client, provider.ToString(), parameters); }
/// <summary> /// Log a user into a Mobile Services application given a provider name. /// </summary> /// <param name="client">The MobileServiceClient instance to login with</param> /// <param name="context">The Android Context to display the Login UI in.</param> /// <param name="provider">Authentication provider to use.</param> /// <param name="uriScheme">The URL scheme of the application.</param> /// <param name="parameters"> /// Provider specific extra parameters that are sent as query string parameters to login endpoint. /// </param> /// <returns>The user record for the authenticated user.</returns> public static Task <MobileServiceUser> LoginAsync(this MobileServiceClient client, Context context, MobileServiceAuthenticationProvider provider, string uriScheme, IDictionary <string, string> parameters) => LoginAsync(client, context, provider.ToString(), uriScheme, parameters);
/// <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> /// <param name="useSingleSignOn"> /// Indicates that single sign-on should be used. Single sign-on requires that the /// application's Package SID be registered with the Windows Azure Mobile Service, but it /// provides a better experience as HTTP cookies are supported so that users do not have to /// login in everytime the application is launched. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> public async Task <MobileServiceUser> SendLoginAsync(MobileServiceAuthenticationProvider provider, JsonObject token, bool useSingleSignOn) { if (this.LoginInProgress) { throw new InvalidOperationException(Resources.Platform_Login_Error_Response); } 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.Client.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token, this.IgnoreFilters); } else { // Use WebAuthenicationBroker to launch server side OAuth flow using the GET endpoint WebAuthenticationResult result = null; if (useSingleSignOn) { string endUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri; Uri startUri = new Uri(this.Client.ApplicationUri, LoginAsyncUriFragment + "/" + providerName + "?sso_end_uri=" + endUri); result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri); } else { Uri startUri = new Uri(this.Client.ApplicationUri, LoginAsyncUriFragment + "/" + providerName); Uri endUri = new Uri(this.Client.ApplicationUri, LoginAsyncDoneUriFragment); 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 index = result.ResponseData.IndexOf("#token="); if (index > 0) { response = JsonValue.Parse(Uri.UnescapeDataString(result.ResponseData.Substring(index + 7))); } else { index = result.ResponseData.IndexOf("#error="); if (index > 0) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, Resources.MobileServiceLogin_Login_Error_Response, Uri.UnescapeDataString(result.ResponseData.Substring(index + 7)))); } else { throw new InvalidOperationException(Resources.Platform_Login_Invalid_Response_Format); } } } // Get the Mobile Services auth token and user data this.Client.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString()); this.Client.CurrentUser.MobileServiceAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString(); } finally { this.LoginInProgress = false; } return(this.Client.CurrentUser); }