/// <summary> /// Gets the WebRedirectAuthenticator. /// </summary> /// <returns>The authenticator.</returns> /// <param name="connection">Connection name.</param> /// <param name="scope">OpenID scope.</param> /// <param name="deviceName">The device name to use if gettting a refresh token.</param> /// <param name="title">Title displayed by WebRedirectAuthenticator, by default is empty.</param> protected virtual async Task <WebRedirectAuthenticator> GetAuthenticator(string connection, string scope, string title = null) { // Generate state to include in startUri var chars = new char[16]; var rand = new Random(); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next((int)'a', (int)'z' + 1); } var redirectUri = this.CallbackUrl; var authorizeUri = !string.IsNullOrWhiteSpace(connection) ? string.Format(Auth0Constants.AuthorizeUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), connection, scope) : string.Format(Auth0Constants.LoginWidgetUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), scope); if (ScopeHasOfflineAccess("offline_access")) { var deviceId = Uri.EscapeDataString(await this.DeviceIdProvider.GetDeviceId()); authorizeUri += string.Format("&device={0}", deviceId); } var state = new string (chars); var startUri = new Uri(authorizeUri + "&state=" + state); var endUri = new Uri(redirectUri); var auth = new WebRedirectAuthenticator(startUri, endUri); auth.ClearCookiesBeforeLogin = false; auth.Title = title; return(auth); }
private WebRedirectAuthenticator GetAuthenticator(string connection, string scope) { // Generate state to include in startUri var chars = new char[16]; var rand = new Random(); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next((int)'a', (int)'z' + 1); } var redirectUri = this.CallbackUrl; var authorizeUri = !string.IsNullOrWhiteSpace(connection) ? string.Format(AuthorizeUrl, this.domain, this.clientId, Uri.EscapeDataString(redirectUri), connection, scope) : string.Format(LoginWidgetUrl, this.domain, this.clientId, Uri.EscapeDataString(redirectUri), scope); var state = new string (chars); var startUri = new Uri(authorizeUri + "&state=" + state); var endUri = new Uri(redirectUri); var auth = new WebRedirectAuthenticator(startUri, endUri); auth.ClearCookiesBeforeLogin = false; return(auth); }
protected override Task<string> LoginAsyncOverride() { var tcs = new TaskCompletionSource<string>(); var auth = new WebRedirectAuthenticator (StartUri, EndUri); auth.ClearCookiesBeforeLogin = false; Intent intent = auth.GetUI (this.context); auth.Error += (sender, e) => { string message = String.Format (CultureInfo.InvariantCulture, Resources.IAuthenticationBroker_AuthenticationFailed, e.Message); InvalidOperationException ex = (e.Exception == null) ? new InvalidOperationException (message) : new InvalidOperationException (message, e.Exception); tcs.TrySetException (ex); }; auth.Completed += (sender, e) => { if (!e.IsAuthenticated) tcs.TrySetException (new InvalidOperationException (Resources.IAuthenticationBroker_AuthenticationCanceled)); else tcs.TrySetResult(e.Account.Properties["token"]); }; context.StartActivity (intent); return tcs.Task; }
/// <summary> /// Opens the URL. /// /// /// </summary> /// <returns><c>true</c>, if URL was opened, <c>false</c> otherwise.</returns> /// <param name="app">App.</param> /// <param name="url">URL.</param> /// <param name="sourceApp">Source app.</param> /// <param name="annotation">Annotation.</param> /// <example> /// <code> /// <!-- /// Info.plist /// --> /// <key>CFBundleURLTypes</key> /// <array> /// <dict> /// <key>CFBundleURLName</key> /// <string>com.example.store</string> /// <key>CFBundleURLTypes</key> /// <string>Viewer</string> /// <key>CFBundleURLSchemes</key> /// <array> /// <string>xamarinauth</string> /// <string>xamarin-auth</string> /// <string>xamarin.auth</string> /// </array> /// </dict> /// </array> /// </code> /// </example> //================================================================= // WalkThrough Step 4 // Intercepting/Catching/Detecting [redirect] url change // App Linking / Deep linking - custom url schemes // public override bool OpenUrl ( UIApplication application, NSUrl url, string sourceApplication, NSObject annotation ) { #if DEBUG System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine("OpenURL Called"); sb.Append(" url = ").AppendLine(url.AbsoluteUrl.ToString()); sb.Append(" application = ").AppendLine(sourceApplication); sb.Append(" annotation = ").AppendLine(annotation?.ToString()); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif //================================================================= // Walthrough Step 4.1 // Intercepting redirect_url and Loading it // Convert iOS NSUrl to C#/netxf/BCL System.Uri - common API System.Uri uri_netfx = new System.Uri(url.AbsoluteString); WebRedirectAuthenticator wre = null; wre = (WebRedirectAuthenticator) global::Xamarin.Auth.XamarinForms.XamarinIOS. AuthenticatorPageRenderer.Authenticator; // load redirect_url Page wre?.OnPageLoading(uri_netfx); //================================================================= return(true); }
public void Manual_Azure () { var a = new WebRedirectAuthenticator ( initialUrl: new Uri ("https://xamarinauth.azure-mobile.net/login/facebook"), redirectUrl: new Uri ("https://xamarinauth.azure-mobile.net/login/done")); var intent = a.GetUI (TestRunner.Shared); TestRunner.Shared.StartActivity (intent); a.Completed += HandleCompleted; }
public void Manual_Azure () { var a = new WebRedirectAuthenticator ( initialUrl: new Uri ("https://xamarinauth.azure-mobile.net/login/facebook"), redirectUrl: new Uri ("https://xamarinauth.azure-mobile.net/login/done")); var vc = a.GetUI (); AppDelegate.SharedViewController.PresentViewController (vc, true, null); a.Completed += HandleCompleted; }
public Task <(string IdToken, string AccessToken)> LoginWithGoogle() { string clientId = null; string redirectUri = null; switch (Device.RuntimePlatform) { case Device.iOS: clientId = AppConstans.IosGoogleClientId; redirectUri = AppConstans.IosReversedGoogleClientId; break; case Device.Android: clientId = AppConstans.AndroidGoogleClientId; redirectUri = AppConstans.AndroidReversedGoogleClientId; break; } redirectUri += ":/oauth2redirect"; _authenticator = new OAuth2Authenticator(clientId, null, "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile", new Uri("https://accounts.google.com/o/oauth2/auth"), new Uri(redirectUri), new Uri("https://www.googleapis.com/oauth2/v4/token"), null, true); var tcs = new TaskCompletionSource <(string IdToken, string AccessToken)>(); _authenticator.Completed += (sender, e) => { if (e.IsAuthenticated && e.Account != null && e.Account.Properties != null) { var properties = e.Account.Properties; tcs.TrySetResult((IdToken: properties["id_token"], AccessToken: properties["access_token"])); } else { tcs.TrySetResult((null, null)); } }; _authenticator.Error += (sender, e) => { tcs.TrySetException(e.Exception ?? new Exception(e.Message)); }; var presenter = new OAuthLoginPresenter(); presenter.Login(_authenticator); return(tcs.Task); }
public void Manual_Azure() { var a = new WebRedirectAuthenticator( initialUrl: new Uri("https://xamarinauth.azure-mobile.net/login/facebook"), redirectUrl: new Uri("https://xamarinauth.azure-mobile.net/login/done")); var intent = a.GetUI(TestRunner.Shared); TestRunner.Shared.StartActivity(intent); a.Completed += HandleCompleted; }
public void PerformAuthentication(WebRedirectAuthenticator authenticator) { if (authenticator == null) { return; } var authViewController = authenticator.GetUI(); PresentViewController(authViewController, true, null); }
protected override void StartLoginUi(object viewReference) { _authenticator = new WebRedirectAuthenticator(GetAuthenticationUri(), GetRedirectUri()); _authenticator.Error += AuthenticatorOnError; _authenticator.Completed += AuthenticatorOnCompleted; var activity = (AppCompatActivity)viewReference; var intent = _authenticator.GetUI(activity); activity.StartActivity(intent); }
public void Manual_Azure() { var a = new WebRedirectAuthenticator( initialUrl: new Uri("https://xamarinauth.azure-mobile.net/login/facebook"), redirectUrl: new Uri("https://xamarinauth.azure-mobile.net/login/done")); var vc = a.GetUI(); AppDelegate.SharedViewController.PresentViewController(vc, true, null); a.Completed += HandleCompleted; }
protected override void StartLoginUi(object viewReference) { _authenticator = new WebRedirectAuthenticator(GetAuthenticationUri(), GetRedirectUri()); _authenticator.Error += AuthenticatorOnError; _authenticator.Completed += AuthenticatorOnCompleted; _dispatcherHelper.ExecuteOnUiThread(() => { _viewController = (UIViewController)viewReference; _viewController.PresentViewController(_authenticator.GetUI(), false, null); }); }
public void OnSamlResponseReceived(string samlResponse) { WebRedirectAuthenticator webRedirectAuthenticator = this.authenticator as WebRedirectAuthenticator; if (webRedirectAuthenticator != null) { string uri = webRedirectAuthenticator.GetRedirectUrl().ToString(); uri += "?SAMLResponse=" + samlResponse; webRedirectAuthenticator.OnPageLoading(new Uri(uri)); this.DismissViewControllerAsync(true); } }
protected override Task <string> LoginAsyncOverride() { var tcs = new TaskCompletionSource <string>(); var auth = new WebRedirectAuthenticator(StartUri, EndUri); auth.ShowUIErrors = false; auth.ClearCookiesBeforeLogin = false; Intent intent = auth.GetUI(this.context); auth.Error += (sender, e) => { string message = String.Format(CultureInfo.InvariantCulture, Resources.IAuthenticationBroker_AuthenticationFailed, e.Message); InvalidOperationException ex = (e.Exception == null) ? new InvalidOperationException(message) : new InvalidOperationException(message, e.Exception); tcs.TrySetException(ex); }; auth.Completed += (sender, e) => { if (!e.IsAuthenticated) { tcs.TrySetException(new InvalidOperationException(Resources.IAuthenticationBroker_AuthenticationCanceled)); } else { tcs.TrySetResult(e.Account.Properties["token"]); } }; context.StartActivity(intent); return(tcs.Task); }
/// <summary> /// Gets the WebRedirectAuthenticator. /// </summary> /// <returns>The authenticator.</returns> /// <param name="connection">Connection name.</param> /// <param name="scope">OpenID scope.</param> /// <param name="deviceName">The device name to use if gettting a refresh token.</param> /// <param name="title">Title displayed by WebRedirectAuthenticator, by default is empty.</param> protected virtual async Task<WebRedirectAuthenticator> GetAuthenticator(string connection, string scope, string title = null) { // Generate state to include in startUri var chars = new char[16]; var rand = new Random (); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1); } var redirectUri = this.CallbackUrl; var authorizeUri = !string.IsNullOrWhiteSpace (connection) ? string.Format(Auth0Constants.AuthorizeUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), connection, scope) : string.Format(Auth0Constants.LoginWidgetUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), scope); if (ScopeHasOfflineAccess("offline_access")) { var deviceId = Uri.EscapeDataString(await this.DeviceIdProvider.GetDeviceId()); authorizeUri += string.Format("&device={0}", deviceId); } var state = new string (chars); var startUri = new Uri (authorizeUri + "&state=" + state); var endUri = new Uri (redirectUri); var auth = new WebRedirectAuthenticator (startUri, endUri); auth.ClearCookiesBeforeLogin = false; auth.Title = title; return auth; }
/// <summary> /// Gets the WebRedirectAuthenticator. /// </summary> /// <returns>The authenticator.</returns> /// <param name="connection">Connection name.</param> /// <param name="scope">OpenID scope.</param> protected virtual WebRedirectAuthenticator GetAuthenticator(string connection, string scope) { // Generate state to include in startUri var chars = new char[16]; var rand = new Random (); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1); } var redirectUri = this.CallbackUrl; var authorizeUri = !string.IsNullOrWhiteSpace (connection) ? string.Format(AuthorizeUrl, this.domain, this.clientId, Uri.EscapeDataString(redirectUri), connection, scope) : string.Format(LoginWidgetUrl, this.domain, this.clientId, Uri.EscapeDataString(redirectUri), scope); var state = new string (chars); var startUri = new Uri (authorizeUri + "&state=" + state); var endUri = new Uri (redirectUri); var auth = new WebRedirectAuthenticator (startUri, endUri); auth.ClearCookiesBeforeLogin = false; return auth; }
protected override Task<string> LoginAsyncOverride() { var tcs = new TaskCompletionSource<string>(); var auth = new WebRedirectAuthenticator(StartUri, EndUri); auth.ShowUIErrors = false; auth.ClearCookiesBeforeLogin = false; UIViewController c = auth.GetUI(); UIViewController controller = null; UIPopoverController popover = null; auth.Error += (o, e) => { NSAction completed = () => { Exception ex = e.Exception ?? new Exception(e.Message); tcs.TrySetException(ex); }; if (controller != null) controller.DismissViewController(true, completed); if (popover != null) { popover.Dismiss(true); completed(); } }; auth.Completed += (o, e) => { NSAction completed = () => { if (!e.IsAuthenticated) tcs.TrySetException(new InvalidOperationException("Authentication was cancelled by the user.")); else tcs.TrySetResult(e.Account.Properties["token"]); }; if (controller != null) controller.DismissViewController(true, completed); if (popover != null) { popover.Dismiss(true); completed(); } }; controller = view as UIViewController; if (controller != null) { controller.PresentViewController(c, true, null); } 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> /// Whether the UIWebView should begin loading data. /// </summary> /// <returns><c>true</c>, if start load was shoulded, <c>false</c> otherwise.</returns> /// <param name="webView">Web view.</param> /// <param name="request">Request.</param> /// <param name="navigationType">Navigation type.</param> public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) { NSUrl nsUrl = request.Url; string msg = null; #if DEBUG StringBuilder sb = new StringBuilder(); sb.AppendLine($"UIWebViewDelegate.ShouldStartLoad "); sb.AppendLine($" nsUrl.AbsoluteString = {nsUrl.AbsoluteString}"); sb.AppendLine($" WebViewConfiguration.IOS.UserAgent = {WebViewConfiguration.IOS.UserAgent}"); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif WebAuthenticator wa = null; WebRedirectAuthenticator wra = null; wa = this.controller.authenticator as WebAuthenticator; wra = this.controller.authenticator as WebRedirectAuthenticator; #if DEBUG if (wa != null) { msg = String.Format("WebAuthenticatorController.authenticator as WebAuthenticator"); System.Diagnostics.Debug.WriteLine(msg); } if (wra != null) { msg = String.Format("WebAuthenticatorController.authenticator as WebRedirectAuthenticator"); System.Diagnostics.Debug.WriteLine(msg); } msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", nsUrl.AbsoluteString); System.Diagnostics.Debug.WriteLine(msg); #endif bool is_loadable_url = false; if (nsUrl != null && !controller.authenticator.HasCompleted) { Uri url; if (Uri.TryCreate(nsUrl.AbsoluteString, UriKind.Absolute, out url)) { string host = url.Host.ToLower(); string scheme = url.Scheme; #if DEBUG msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", url.AbsoluteUri); System.Diagnostics.Debug.WriteLine(msg); msg = string.Format(" Host = {0}", host); System.Diagnostics.Debug.WriteLine(msg); msg = string.Format(" Scheme = {0}", scheme); System.Diagnostics.Debug.WriteLine(msg); #endif if (host == "localhost" || host == "127.0.0.1" || host == "::1") { is_loadable_url = false; this.controller.DismissViewControllerAsync(true); } else { is_loadable_url = true; } controller.authenticator.OnPageLoading(url); } } if (wra != null) { // TODO: class refactoring // OAuth2Authenticator is WebRedirectAuthenticator wra wra.IsLoadableRedirectUri = is_loadable_url; return(wra.IsLoadableRedirectUri); } else if (wa != null) { // TODO: class refactoring // OAuth1Authenticator is WebRedirectAuthenticator wra return(is_loadable_url); } return(false); }
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); }
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> /// Whether the UIWebView should begin loading data. /// </summary> /// <returns><c>true</c>, if start load was shoulded, <c>false</c> otherwise.</returns> /// <param name="webView">Web view.</param> /// <param name="request">Request.</param> /// <param name="navigationType">Navigation type.</param> public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) { NSUrl nsUrl = request.Url; string msg = null; #if DEBUG StringBuilder sb = new StringBuilder(); sb.AppendLine($"UIWebViewDelegate.ShouldStartLoad "); sb.AppendLine($" nsUrl.AbsoluteString = {nsUrl.AbsoluteString}"); sb.AppendLine($" WebViewConfiguration.IOS.UserAgent = {WebViewConfiguration.IOS.UserAgent}"); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif WebAuthenticator wa = null; WebRedirectAuthenticator wra = null; wa = this.controller.authenticator as WebAuthenticator; wra = this.controller.authenticator as WebRedirectAuthenticator; #if DEBUG if (wa != null) { msg = String.Format("WebAuthenticatorController.authenticator as WebAuthenticator"); System.Diagnostics.Debug.WriteLine(msg); } if (wra != null) { msg = String.Format("WebAuthenticatorController.authenticator as WebRedirectAuthenticator"); System.Diagnostics.Debug.WriteLine(msg); } msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", nsUrl.AbsoluteString); System.Diagnostics.Debug.WriteLine(msg); #endif bool is_loadable_url = false; if (nsUrl != null && !controller.authenticator.HasCompleted) { Uri url; if (Uri.TryCreate(nsUrl.AbsoluteString, UriKind.Absolute, out url)) { string host = url.Host.ToLower(); string scheme = url.Scheme; #if DEBUG msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", url.AbsoluteUri); System.Diagnostics.Debug.WriteLine(msg); msg = string.Format(" Host = {0}", host); System.Diagnostics.Debug.WriteLine(msg); msg = string.Format(" Scheme = {0}", scheme); System.Diagnostics.Debug.WriteLine(msg); #endif if (host == "localhost" || host == "127.0.0.1" || host == "::1") { is_loadable_url = false; this.controller.DismissViewControllerAsync(true); } else { is_loadable_url = true; } // COSMOS if (request.Body != null) { Encoding encoding = Encoding.UTF8; if (request.Headers != null && request.Headers.ContainsKey(new NSString("Content-Type"))) { encoding = WebEx.GetEncodingFromContentType(request.Headers[new NSString("Content-Type")].ToString()); } byte[] dataBytes = new byte[request.Body.Length]; System.Runtime.InteropServices.Marshal.Copy(request.Body.Bytes, dataBytes, 0, Convert.ToInt32(request.Body.Length)); string bodyString = encoding.GetString(dataBytes); System.Collections.Generic.IDictionary <string, string> formParams = WebEx.FormDecode(bodyString); var concatenatedParameters = formParams.Select(pair => $"{System.Net.WebUtility.UrlEncode(pair.Key)}={System.Net.WebUtility.UrlEncode(pair.Value)}"); var query = string.Join("&", concatenatedParameters); var uriString = string.IsNullOrEmpty(url.Query) ? url.OriginalString + $"?{query}" : url.OriginalString + $"&{query}"; url = new Uri(uriString); } // controller.authenticator.OnPageLoading(url); } } if (wra != null) { // TODO: class refactoring // OAuth2Authenticator is WebRedirectAuthenticator wra wra.IsLoadableRedirectUri = is_loadable_url; return(wra.IsLoadableRedirectUri); } else if (wa != null) { // TODO: class refactoring // OAuth1Authenticator is WebRedirectAuthenticator wra return(is_loadable_url); } return(false); }
/// <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); }
protected override Task <string> LoginAsyncOverride() { var tcs = new TaskCompletionSource <string>(); var auth = new WebRedirectAuthenticator(StartUri, EndUri); auth.ShowUIErrors = false; auth.ClearCookiesBeforeLogin = false; UIViewController c = auth.GetUI(); UIViewController controller = null; UIPopoverController popover = null; auth.Error += (o, e) => { NSAction completed = () => { Exception ex = e.Exception ?? new Exception(e.Message); tcs.TrySetException(ex); }; if (controller != null) { controller.DismissViewController(true, completed); } if (popover != null) { popover.Dismiss(true); completed(); } }; auth.Completed += (o, e) => { NSAction completed = () => { if (!e.IsAuthenticated) { tcs.TrySetException(new InvalidOperationException(Resources.IAuthenticationBroker_AuthenticationCanceled)); } else { tcs.TrySetResult(e.Account.Properties["token"]); } }; if (controller != null) { controller.DismissViewController(true, completed); } if (popover != null) { popover.Dismiss(true); completed(); } }; controller = view as UIViewController; if (controller != null) { controller.PresentViewController(c, true, null); } 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="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; }