public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layout = new FrameLayout(Activity); layout.SetBackgroundColor(Color.White); // // Build the UI // webView = new WebView(Activity) { Id = 42 }; webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new Client(this)); layout.AddView(webView); // // Restore the UI state or start over // if (savedInstanceState != null) { webView.RestoreState(savedInstanceState); } else { if (Activity.Intent.GetBooleanExtra("ClearCookies", false)) { WebAuthenticator.ClearCookies(); } } return(layout); }
public WebAuthenticatorView(WebAuthenticator authenticator, UIViewController parent, UIView loadingView = null) { this.authenticator = authenticator; this.parent = parent; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; var bounds = new RectangleF(0, 60, parent.View.Bounds.Width, parent.View.Bounds.Height - 60); if (!(parent is WebAuthenticatorController)) { bounds = new RectangleF(0, 20, parent.View.Bounds.Width, parent.View.Bounds.Height - 20); } webView = new UIWebView(bounds) { Delegate = new WebViewDelegate(this), Hidden = true }; if (loadingView != null) { Add(loadingView); } Add(webView); BeginLoadingInitialUrl(); }
protected void ProviderSamplesList_Handle_ItemSelected(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e) { Type selection_type = e.SelectedItem.GetType(); string selection = selection_type.ToString().Replace("Xamarin.Auth.ProviderSamples.", ""); System.Diagnostics.Debug.WriteLine($" Provider Sample"); System.Diagnostics.Debug.WriteLine($" Selection = {selection}"); Xamarin.Auth.WebAuthenticator authenticator = null; Xamarin.Auth.ProviderSamples.Helpers.OAuth1 oauth1 = null; Xamarin.Auth.ProviderSamples.Helpers.OAuth2 oauth2 = null; oauth2 = Activator.CreateInstance(selection_type) as Xamarin.Auth.ProviderSamples.Helpers.OAuth2; if (null == oauth2) { oauth1 = Activator.CreateInstance(selection_type) as Xamarin.Auth.ProviderSamples.Helpers.OAuth1; if (null == oauth1) { throw new ArgumentException("Not OAuth object!"); } authenticator = Map(oauth1); } authenticator = Map(oauth2); return; }
void BeginLoadingInitialUrl() { activity.StartAnimating(); authenticator.GetInitialUrlAsync().ContinueWith(t => { if (t.IsFaulted) { keepTryingAfterError = false; authenticator.OnError(t.Exception); activity.StopAnimating(); } else { // Delete cookies so we can work with multiple accounts if (this.authenticator.ClearCookiesBeforeLogin) { WebAuthenticator.ClearCookies(); } // // Begin displaying the page // LoadInitialUrl(t.Result); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public WebAuthenticatorController(WebAuthenticator authenticator) { this.authenticator = authenticator; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; // // Create the UI // Title = authenticator.Title; NavigationItem.LeftBarButtonItem = new UIBarButtonItem( UIBarButtonSystemItem.Cancel, delegate { Cancel(); }); activity = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.White); NavigationItem.RightBarButtonItem = new UIBarButtonItem(activity); webView = new UIWebView(View.Bounds) { Delegate = new WebViewDelegate(this), AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, }; View.AddSubview(webView); View.BackgroundColor = UIColor.Black; // // Locate our initial URL // BeginLoadingInitialUrl(); }
public WebAuthenticatorController(WebAuthenticator authenticator) { this.authenticator = authenticator; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; // // Create the UI // Title = authenticator.Title; if (authenticator.AllowCancel) { NavigationItem.LeftBarButtonItem = new UIBarButtonItem( UIBarButtonSystemItem.Cancel, delegate { Cancel(); # region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// OAuth2Authenticator changes to work with joind.in OAuth #91 /// https://github.com/xamarin/Xamarin.Auth/pull/91 /// DismissViewControllerAsync(true); ///--------------------------------------------------------------------------------------- # endregion });
public WebAuthenticatorController(WebAuthenticator authenticator, UIView loadingView = null) { this.authenticator = authenticator; Title = authenticator.Title; if (authenticator.AllowCancel) { NavigationItem.LeftBarButtonItem = new UIBarButtonItem( UIBarButtonSystemItem.Cancel, delegate { view.Cancel(); }); } if (loadingView == null) { loadingView = new UIView(View.Bounds); loadingView.BackgroundColor = UIColor.White; float labelHeight = 22; float labelWidth = loadingView.Frame.Width - 20; // derive the center x and y float centerX = loadingView.Frame.Width / 2; float centerY = loadingView.Frame.Height / 2; var activitySpinner = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.Gray); activitySpinner.Frame = new RectangleF( centerX - (activitySpinner.Frame.Width / 2), centerY - activitySpinner.Frame.Height - 20, activitySpinner.Frame.Width, activitySpinner.Frame.Height); activitySpinner.AutoresizingMask = UIViewAutoresizing.FlexibleMargins; loadingView.AddSubview(activitySpinner); activitySpinner.StartAnimating(); var loadingLabel = new UILabel(new RectangleF( centerX - (labelWidth / 2), centerY + 20, labelWidth, labelHeight )); loadingLabel.BackgroundColor = UIColor.Clear; loadingLabel.TextColor = UIColor.Black; loadingLabel.Text = "Logging in..."; loadingLabel.TextAlignment = UITextAlignment.Center; loadingLabel.AutoresizingMask = UIViewAutoresizing.FlexibleMargins; loadingView.AddSubview(loadingLabel); } view = new WebAuthenticatorView(authenticator, this, loadingView); view.Frame = View.Bounds; View.Add(view); }
public static WebAuthenticatorFragment NewInstance(WebAuthenticator authenticator) { var frag = new WebAuthenticatorFragment { Arguments = new Bundle(), Authenticator = authenticator }; return(frag); }
public AuthenticatorControl(WebAuthenticator authenticator) { if (authenticator == null) { throw new ArgumentNullException("Authenticator cannot be null."); } this.authenticator = authenticator; this.webView = new WebView(); webView.NavigationCompleted += webView_NavigationCompleted; Content = webView; Loaded += AuthenticatorControl_Loaded; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { authenticator = (OAuth2Authenticator)e.Parameter; url_initial = this.authenticator.GetInitialUrlAsync().Result; this.browser.Navigate(url_initial); System.Diagnostics.Debug.WriteLine("OnNavigatedTo authenticator = " + authenticator.Title); authenticator.Completed += auth_Completed; authenticator.Error += auth_Error; url_initial = await authenticator.GetInitialUrlAsync(); base.OnNavigatedTo(e); return; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // // Load the state either from a configuration change or from the intent. // state = LastNonConfigurationInstance as State; if (state == null && Intent.HasExtra("StateKey")) { var stateKey = Intent.GetStringExtra("StateKey"); state = StateRepo.Remove(stateKey); } if (state == null) { Finish(); return; } Title = state.Authenticator.Title; // // Watch for completion // state.Authenticator.Completed += (s, e) => { SetResult(e.IsAuthenticated ? Result.Ok : Result.Canceled); Finish(); }; state.Authenticator.Error += (s, e) => { if (e.Exception != null) { this.ShowError("Authentication Error", e.Exception); } else { this.ShowError("Authentication Error", e.Message); } BeginLoadingInitialUrl(); }; // // Build the UI // webView = new WebView(this) { Id = 42, }; webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new Client(this)); SetContentView(webView); // // Restore the UI state or start over // if (savedInstanceState != null) { webView.RestoreState(savedInstanceState); } else { if (Intent.GetBooleanExtra("ClearCookies", true)) { WebAuthenticator.ClearCookies(); } BeginLoadingInitialUrl(); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // // Load the state either from a configuration change or from the intent. // state = LastNonConfigurationInstance as State; if (state == null && Intent.HasExtra("StateKey")) { var stateKey = Intent.GetStringExtra("StateKey"); state = StateRepo.Remove(stateKey); } if (state == null) { Finish(); return; } Title = state.Authenticator.Title; // // Watch for completion // state.Authenticator.Completed += (s, e) => { SetResult(e.IsAuthenticated ? Result.Ok : Result.Canceled); #region ///------------------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// Added IsAuthenticated check #88 /// https://github.com/xamarin/Xamarin.Auth/pull/88 if (e.IsAuthenticated) { if (state.Authenticator.GetAccountResult != null) { var accountResult = state.Authenticator.GetAccountResult(e.Account); Bundle result = new Bundle(); result.PutString(global::Android.Accounts.AccountManager.KeyAccountType, accountResult.AccountType); result.PutString(global::Android.Accounts.AccountManager.KeyAccountName, accountResult.Name); result.PutString(global::Android.Accounts.AccountManager.KeyAuthtoken, accountResult.Token); result.PutString(global::Android.Accounts.AccountManager.KeyAccountAuthenticatorResponse, e.Account.Serialize()); SetAccountAuthenticatorResult(result); } } ///------------------------------------------------------------------------------------------------- #endregion Finish(); }; state.Authenticator.Error += (s, e) => { if (!state.Authenticator.ShowErrors) { return; } if (e.Exception != null) { this.ShowError("Authentication Error e.Exception = ", e.Exception); } else { this.ShowError("Authentication Error e.Message = ", e.Message); } BeginLoadingInitialUrl(); }; //--------------------------------------------------------------------------------- // // Build the UI // webView = new WebView(this) { Id = 42, }; webView.Settings.UserAgentString = WebViewConfiguration.Android.UserAgent; Client web_view_client = new Client(this); // UserAgent set in the class webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(web_view_client); SetContentView(webView); //--------------------------------------------------------------------------------- // // Restore the UI state or start over // if (savedInstanceState != null) { webView.RestoreState(savedInstanceState); } else { if (Intent.GetBooleanExtra("ClearCookies", true)) { WebAuthenticator.ClearCookies(); } BeginLoadingInitialUrl(); } return; }
public WebAuthenticatorController(WebAuthenticator authenticator, bool is_using_wkwebview) { WebViewConfiguration.IOS.IsUsingWKWebView = is_using_wkwebview; this.authenticator = authenticator; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; // // Create the UI // if (authenticator.AllowCancel) { NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( UIBarButtonSystemItem.Cancel, delegate { Cancel(); #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// OAuth2Authenticator changes to work with joind.in OAuth #91 /// https://github.com/xamarin/Xamarin.Auth/pull/91 /// DismissViewControllerAsync(true); ///--------------------------------------------------------------------------------------- #endregion } ); } activity = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.White); NavigationItem.RightBarButtonItem = new UIBarButtonItem(activity); if (WebViewConfiguration.IOS.IsUsingWKWebView == false) { #if DEBUG StringBuilder sb1 = new StringBuilder(); sb1.Append("Embedded WebView using - UIWebView"); System.Diagnostics.Debug.WriteLine(sb1.ToString()); #endif ui_web_view = new UIWebView(View.Bounds) { Delegate = new UIWebViewDelegate(this), AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, }; web_view = ui_web_view; View.AddSubview((UIWebView)web_view); } else { #if DEBUG StringBuilder sb1 = new StringBuilder(); sb1.Append("Embedded WebView using - WKWebView"); System.Diagnostics.Debug.WriteLine(sb1.ToString()); #endif var wk_web_view_configuration = new WebKit.WKWebViewConfiguration(); if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { wk_web_view_configuration.WebsiteDataStore = WKWebsiteDataStore.NonPersistentDataStore; } wk_web_view = new WebKit.WKWebView(View.Frame, wk_web_view_configuration) { UIDelegate = new WKWebViewUIDelegate(this), NavigationDelegate = new WKWebViewNavigationDelegate(this), AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, // cheating! // http://www.useragentstring.com/pages/useragentstring.php?typ=Browser CustomUserAgent = WebViewConfiguration.IOS.UserAgent, }; web_view = wk_web_view; View.AddSubview((WKWebView)web_view); } #if DEBUG authenticator.Title = "Auth " + web_view.GetType().ToString(); #endif Title = authenticator.Title; View.BackgroundColor = UIColor.Black; // InvalidOperation - either delegates or events! //this.webView.LoadFinished += WebView_LoadFinished; // // Locate our initial URL // BeginLoadingInitialUrl(); #if DEBUG StringBuilder sb = new StringBuilder(); sb.AppendLine($"WebAuthenticatorController "); sb.AppendLine($" WebViewConfiguration.IsUsingWKWebView = {WebViewConfiguration.IOS.IsUsingWKWebView}"); sb.AppendLine($" authenticator.IsUsingNativeUI = {authenticator.IsUsingNativeUI}"); sb.AppendLine($" authenticator.Title = {authenticator.Title}"); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif return; }
public WebAuthenticatorController(WebAuthenticator authenticator) : this(authenticator, WebViewConfiguration.IOS.IsUsingWKWebView) { return; }
public WebAuthenticatorController(WebAuthenticator authenticator, bool is_using_wkwebview) { WebViewConfiguration.IOS.IsUsingWKWebView = is_using_wkwebview; this.authenticator = authenticator; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; // // Create the UI // if (authenticator.AllowCancel) { NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( UIBarButtonSystemItem.Cancel, delegate { Cancel(); #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// OAuth2Authenticator changes to work with joind.in OAuth #91 /// https://github.com/xamarin/Xamarin.Auth/pull/91 /// DismissViewControllerAsync(true); ///--------------------------------------------------------------------------------------- #endregion } ); } activity = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.White); NavigationItem.RightBarButtonItem = new UIBarButtonItem(activity); if (WebViewConfiguration.IOS.IsUsingWKWebView == false) { // UIWebView #if DEBUG StringBuilder sb1 = new StringBuilder(); sb1.Append("Embedded WebView using - UIWebView"); System.Diagnostics.Debug.WriteLine(sb1.ToString()); #endif web_view = PrepareUIWebView(); this.View.AddSubview((UIWebView)web_view); } else { // WKWebView - availabilty and fallback is done in PrepareWKWebView() #if DEBUG StringBuilder sb1 = new StringBuilder(); sb1.Append("Embedded WebView using - WKWebView"); System.Diagnostics.Debug.WriteLine(sb1.ToString()); #endif web_view = PrepareWKWebView(); this.View.AddSubview((WKWebView)web_view); } #if DEBUG authenticator.Title = "Auth " + web_view.GetType().ToString(); #endif Title = authenticator.Title; View.BackgroundColor = UIColor.Black; // InvalidOperation - either delegates or events! //this.webView.LoadFinished += WebView_LoadFinished; // // Locate our initial URL // BeginLoadingInitialUrl(); #if DEBUG StringBuilder sb = new StringBuilder(); sb.AppendLine($"WebAuthenticatorController "); sb.AppendLine($" WebViewConfiguration.IsUsingWKWebView = {WebViewConfiguration.IOS.IsUsingWKWebView}"); sb.AppendLine($" authenticator.IsUsingNativeUI = {authenticator.IsUsingNativeUI}"); sb.AppendLine($" authenticator.Title = {authenticator.Title}"); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif return; }
protected void Google() { authenticator = new Xamarin.Auth.OAuth2Authenticator ( clientId: new Func <string> ( () => { string retval_client_id = "oops something is wrong!"; // some people are sending the same AppID for google and other providers // not sure, but google (and others) might check AppID for Native/Installed apps // Android and iOS against UserAgent in request from // CustomTabs and SFSafariViewContorller // TODO: send deliberately wrong AppID and note behaviour for the future // fitbit does not care - server side setup is quite liberal switch (Xamarin.Forms.Device.RuntimePlatform) { case "Android": retval_client_id = "1093596514437-d3rpjj7clslhdg3uv365qpodsl5tq4fn.apps.googleusercontent.com"; break; case "iOS": retval_client_id = "1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh.apps.googleusercontent.com"; break; case "Windows": retval_client_id = "1093596514437-t7ocfv5tqaskkd53llpfi3dtdvk4t35h.apps.googleusercontent.com"; break; } return(retval_client_id); } ).Invoke(), clientSecret: null, // null or "" authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"), accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"), redirectUrl: new Func <Uri> ( () => { string uri = null; // some people are sending the same AppID for google and other providers // not sure, but google (and others) might check AppID for Native/Installed apps // Android and iOS against UserAgent in request from // CustomTabs and SFSafariViewContorller // TODO: send deliberately wrong AppID and note behaviour for the future // fitbit does not care - server side setup is quite liberal switch (Xamarin.Forms.Device.RuntimePlatform) { case "Android": uri = "com.xamarin.traditional.standard.samples.oauth.providers.android:/oauth2redirect" //"com.googleusercontent.apps.1093596514437-d3rpjj7clslhdg3uv365qpodsl5tq4fn:/oauth2redirect" ; break; case "iOS": uri = "com.xamarin.traditional.standard.samples.oauth.providers.ios:/oauth2redirect" //"com.googleusercontent.apps.1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh:/oauth2redirect" ; break; case "Windows": uri = "com.xamarin.auth.windows:/oauth2redirect" //"com.googleusercontent.apps.1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh:/oauth2redirect" ; break; } return(new Uri(uri)); } ).Invoke(), scope: //"profile" "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login" , getUsernameAsync: null, isUsingNativeUI: Settings.IsUsingNativeUI ) { AllowCancel = true, }; authenticator.Completed += (s, ea) => { StringBuilder sb = new StringBuilder(); if (ea.Account != null && ea.Account.Properties != null) { sb.Append("Token = ").AppendLine($"{ea.Account.Properties["access_token"]}"); } else { sb.Append("Not authenticated ").AppendLine($"Account.Properties does not exist"); } DisplayAlert ( "Authentication Results", sb.ToString(), "OK" ); return; }; authenticator.Error += (s, ea) => { StringBuilder sb = new StringBuilder(); sb.Append("Error = ").AppendLine($"{ea.Message}"); DisplayAlert ( "Authentication Error", sb.ToString(), "OK" ); return; }; // after initialization (creation and event subscribing) exposing local object AuthenticationState.Authenticator = authenticator; this.PresentUILoginScreen(authenticator); return; }
private void ButtonTestUserAgent_Clicked(object sender, EventArgs e) { string user_agent = entryUserAgent.Text; EmbeddedWebViewConfiguration webview_conf; webview_conf = new EmbeddedWebViewConfiguration { UserAgent = user_agent, IsUsingWKWebView = Settings.IsIOSUsingWKWebView }; authenticator = new Xamarin.Auth.OAuth2Authenticator ( clientId: new Func <string> ( () => { string retval_client_id = "not used!"; return(retval_client_id); } ).Invoke(), //clientSecret: null, // null or "" authorizeUrl: new Func <Uri> ( () => { string uri = null; uri = "http://www.whatsmyua.info/"; return(new Uri(uri)); } ).Invoke(), //accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"), redirectUrl: new Func <Uri> ( () => { string uri = null; if (Settings.IsUsingNativeUI) { uri = //"fb1889013594699403://localhost/path" //"fb1889013594699403://xamarin.com" $"https://localhost" ; } else { uri = //"https://localhost/path" $"https://localhost" ; } return(new Uri(uri)); } ).Invoke(), scope: "", // "basic", "email", getUsernameAsync: null, isUsingNativeUI: Settings.IsUsingNativeUI ) { AllowCancel = true, }; this.PresentUILoginScreen(authenticator); return; }
/// <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}"); 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); }
public NativeAuthSafariViewControllerDelegate(WebAuthenticator wa) { authenticator = wa; return; }