protected async override void OnElementChanged(VisualElementChangedEventArgs e) { // Call the method on the base base.OnElementChanged(e); // Exit if the element (Page) is null if (e.OldElement != null || Element == null) { return; } // Set up the AuthenticationManager to challenge for ArcGIS Online credentials UpdateAuthenticationManager(); // Force an OAuth challenge var info = new CredentialRequestInfo { AuthenticationType = AuthenticationType.Token, ServiceUri = new Uri(OAuthPage.PortalUrl) }; await AuthenticationManager.Current.GetCredentialAsync(info, false); // Open the desired web map (portal item) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(OAuthPage.PortalUrl)); PortalItem item = await PortalItem.CreateAsync(portal, OAuthPage.WebMapId); // Create a map Map myMap = new Map(item); // Set the MyMap property on the shared form to display the map in the map view var oauthPage = e.NewElement as OAuthPage; oauthPage.MyMap = myMap; }
private async Task<Credential> GetUserCredentialsFromUI(CredentialRequestInfo info) { // Show the login UI try { // Create a new LoginInfo to store the entered username and password // Pass the CredentialRequestInfo object so the resource URI can be stored var loginInputInfo = new LoginInfo(info); // Set the login UI data context with the LoginInfo loginPanel.DataContext = loginInputInfo; // Show the login UI loginPanel.Visibility = Visibility.Visible; // Create a new task completion source to return the user's login when complete // Set the login UI data context (LoginInfo object) as the AsyncState so it can be retrieved later _loginTaskCompletionSource = new TaskCompletionSource<Credential>(loginPanel.DataContext); // Return the task from the completion source // When the login button on the UI is clicked, the info will be returned for creating the credential return await _loginTaskCompletionSource.Task; } finally { // Hide the login UI loginPanel.Visibility = Visibility.Collapsed; } }
private async Task<Credential> Challenge(CredentialRequestInfo info) { // Call code to get user credentials // Make sure it runs on the UI thread if (this.Dispatcher == null) { // No current dispatcher, code is already running on the UI thread return await GetUserCredentialsFromUI(info); } else { // Use the dispatcher to invoke the challenge UI await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { await GetUserCredentialsFromUI(info); } catch { // Login was canceled or unsuccessful, dialog will close } }); } // Use the task completion source to return the results return await _loginTaskCompletionSource.Task; }
/// <summary> /// Base Challenge method that dispatches to the UI thread if necessary to create a credential /// </summary> /// <param name="info">Information about a secured resource (its URI, for example)</param> /// <returns>A task that returns a credential for attempting access to a secured resource</returns> private async Task<Credential> Challenge(CredentialRequestInfo info) { // Get the dispatcher for the UI thread var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; // If no dispatcher, call the ChallengeUI method directly to get user input if (dispatcher == null) { return await ChallengeUI(info); } else { // Use the dispatcher to show the login panel on the UI thread, then await completion of the task await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { // Call the method that shows the login panel and creates a credential await ChallengeUI(info); } catch (TaskCanceledException) { // The user clicked the "Cancel" button, login panel will close } catch (Exception ex) { // Show exception message ErrorText.Text = ex.Message; } }); // return the task return await _loginTaskCompletionSrc.Task; } }
/// <summary> /// Handle challenges for a secured resource by prompting for a client certificate /// </summary> public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // Use the X509Store to get available certificates var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true); // Ask the user to select a certificate to use certificates = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate", "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection); // Create a new CertificateCredential using the chosen certificate credential = new CertificateCredential(certificates[0]) { ServiceUri = SecuredPortalUrl }; } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } // Return the CertificateCredential for the secured portal return credential; }
private async void OnSaveMapClick(object sender, RoutedEventArgs e) { try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo challengeRequest = new CredentialRequestInfo(); // Use the OAuth implicit grant flow challengeRequest.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with (ArcGIS Online) challengeRequest.ServiceUri = new Uri("https://www.arcgis.com/sharing/rest"); // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); // Get information for the new portal item var title = TitleTextBox.Text; var description = DescriptionTextBox.Text; var tags = TagsTextBox.Text.Split(','); // Throw an exception if the text is null or empty for title or description if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description)) { throw new Exception("Title and description are required"); } // Get current map extent (viewpoint) for the map initial extent var currentViewpoint = MyMapView.GetCurrentViewpoint(Esri.ArcGISRuntime.Mapping.ViewpointType.BoundingGeometry); // See if the map has already been saved if (!_mapViewModel.MapIsSaved) { // Call the SaveNewMapAsync method on the view model, pass in the required info await _mapViewModel.SaveNewMapAsync(currentViewpoint, title, description, tags); // Report success MessageBox.Show("Map '" + title + "' was saved to your portal"); } else { // Map has previously been saved as a portal item, update it (title, description, and tags will remain the same) _mapViewModel.UpdateMapItem(); // Report success MessageBox.Show("Changes to '" + title + "' were updated to the portal."); } } catch (Exception ex) { // Report error MessageBox.Show("Error while saving: " + ex.Message); } }
/// <summary> /// Prompts the user for a credential (username/password) if access to a secured resource is attempted. /// </summary> /// <param name="info">Information about a secured resource (its URI, for example)</param> /// <returns>A credential to use when attempting access to a secured resource</returns> public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // Showing a new window with login UI (username/password) must occur on the UI thread credential = this.Dispatcher.Invoke(new Func<Credential>(() => { Credential cred = null; // Exit if the user clicked "Cancel" in the login window // (otherwise, if the user can't provide credentials for a resource they will continue to be challenged) if (_cancelledLogin) { _cancelledLogin = false; return null; } // Create a new login window var win = new LoginWindow(); win.Owner = this; // Show the window to get user input (if cancelled, false is returned) _cancelledLogin = (win.ShowDialog() == false); if (!_cancelledLogin) { // Get the credential information provided var username = win.UsernameTextBox.Text; var password = win.PasswordTextBox.Password; var domain = win.DomainTextBox.Text; // Create a new network credential using the user input and the URI of the resource cred = new ArcGISNetworkCredential() { Credentials = new NetworkCredential(username, password, domain), ServiceUri = info.ServiceUri }; } // Return the credential return cred; }) ); } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } // Add the credential to the IdentityManager IdentityManager.Current.AddCredential(credential); // Return the credential return credential; }
private async void OnLoadMapClicked(object sender, EventArgs e) { // Challenge the user for portal credentials CredentialRequestInfo loginInfo = new CredentialRequestInfo(); // Use the OAuth implicit grant flow loginInfo.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with loginInfo.ServiceUri = new Uri(PortalUrl); try { // Get a reference to the (singleton) AuthenticationManager for the app AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler await thisAuthenticationManager.GetCredentialAsync(loginInfo, false); // Access the portal ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(PortalUrl)); // Get the item (web map) from the portal PortalItem item = await PortalItem.CreateAsync(portal, WebMapId); // Make sure it's a web map if (item.Type != PortalItemType.WebMap) { return; } // Display the web map in the map view Map webMap = new Map(item); _myMapView.Map = webMap; } catch (System.OperationCanceledException) { // User canceled the login var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Cancel"); alertBuilder.SetMessage("Portal login was canceled."); alertBuilder.Show(); } catch(Exception ex) { // Other exception var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } }
// Base Challenge method that dispatches to the UI thread if necessary private async Task<Credential> Challenge(CredentialRequestInfo cri) { if (Dispatcher == null) { return await ChallengeUI(cri); } else { return await Dispatcher.Invoke(() => ChallengeUI(cri)); } }
/// <summary> /// Generate the credentials with the existing credentials or challenge the user to enter credentials. /// </summary> public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { OAuthTokenCredential credential = null; try { // Portal "single sign in" check when trying to load webmap if (info.Response != null && info.ServiceUri.StartsWith(MyServerUrl)) { Credential existingCredential = IdentityManager.Current.FindCredential(info.ServiceUri); if (existingCredential != null) { // Already logged in and current user does not have access throw new Exception("Current logged in user does not have access."); } } // Modify generate token options if necessary if (info.GenerateTokenOptions == null) info.GenerateTokenOptions = new GenerateTokenOptions(); // Identity Manager will handle challenging the user for credentials credential = await IdentityManager.Current.GenerateCredentialAsync( info.ServiceUri, info.GenerateTokenOptions ) as OAuthTokenCredential; // Switch to UI thread to change control state and content this.Dispatcher.Invoke( (Action)(() => { SignOutButton.IsEnabled = true; SignInButton.IsEnabled = false; LoadWebMapButton.IsEnabled = true; LoggedInUserName.Text = string.Format("Logged in as: {0}", credential.UserName); LoggedInUserName.Visibility = Visibility.Visible; })); // Store the RefreshToken if (credential.OAuthRefreshToken != null) StoreRefreshToken(credential.OAuthRefreshToken); // Not a challenge, user initiated directly if (info.Response == null) IdentityManager.Current.AddCredential(credential); } catch (Exception ex) { MessageBox.Show(ex.Message); } return credential; }
private async Task<Credential> Challenge(CredentialRequestInfo info) { // Call code to get user credentials // Make sure it runs on the UI thread if (this.Dispatcher == null) { // No current dispatcher, code is already running on the UI thread return await GetUserCredentialsFromUI(info); } else { // Use the dispatcher to invoke the challenge UI return await this.Dispatcher.Invoke(() => GetUserCredentialsFromUI(info)); } }
// Challenge method that prompts for username / password private async Task<Credential> ChallengeUI(CredentialRequestInfo cri) { try { loginPanel.DataContext = new LoginInfo(cri); _loginTCS = new TaskCompletionSource<Credential>(loginPanel.DataContext); loginPanel.Visibility = Visibility.Visible; return await _loginTCS.Task; } finally { loginPanel.Visibility = Visibility.Collapsed; } }
// AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential private async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { // Return if authentication is already in process if (_loginTaskCompletionSrc != null && !_loginTaskCompletionSrc.Task.IsCanceled) { return null; } // Create a new TaskCompletionSource for the login operation // (passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property) _loginTaskCompletionSrc = new TaskCompletionSource<Credential>(info); // Show the login controls on the UI thread // OnLoginInfoEntered event will return the values entered (username, password, and domain) Device.BeginInvokeOnMainThread(async() => await Navigation.PushAsync(_loginPage)); // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button) return await _loginTaskCompletionSrc.Task; }
/// <summary> /// Forwards credential request info using Dispatcher to enable access to UI elements. /// </summary> private async Task<Credential> GetCredentialAsync(CredentialRequestInfo info) { var tcs = new TaskCompletionSource<Credential>(); if (Dispatcher == null) tcs.TrySetResult(await GetCredentialUIAsync(info)); else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(async () => { tcs.TrySetResult(await GetCredentialUIAsync(info)); })); } var credential = await tcs.Task; return credential; }
// Base Challenge method that dispatches to the UI thread if necessary private async Task<Credential> Challenge(CredentialRequestInfo cri) { var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; if (dispatcher == null) { return await ChallengeUI(cri); } else { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await ChallengeUI(cri); }); return await _loginTCS.Task; } }
// Challenge method that checks for service access with known credentials private async Task<Credential> Challenge_KnownCredentials(CredentialRequestInfo cri) { try { // Obtain credentials from a secure source string username = "******"; string password = (cri.ServiceUri.Contains("USA_secure_user1")) ? "user1" : "pass.word1"; return await IdentityManager.Current.GenerateCredentialAsync(cri.ServiceUri, username, password, cri.GenerateTokenOptions); } catch (Exception ex) { var _x = new MessageDialog("Access to " + cri.ServiceUri + " denied. " + ex.Message, "Credential Error").ShowAsync(); } return await Task.FromResult<Credential>(null); }
// Challenge method that checks for service access with known credentials //private async Task<IdentityManager.Credential> Challenge_KnownCredentials(IdentityManager.CredentialRequestInfo cri) //{ // try // { // // Obtain credentials from a secure source // string username = "******"; // string password = (cri.ServiceUri.Contains("USA_secure_user1")) ? "user1" : "pass.word1"; // return await IdentityManager.Current.GenerateCredentialAsync(cri.ServiceUri, username, password, cri.GenerateTokenOptions); // } // catch (Exception ex) // { // var _x = new MessageDialog("Access to " + cri.ServiceUri + " denied. " + ex.Message, "Credential Error").ShowAsync(); // } // return await Task.FromResult<IdentityManager.Credential>(null); //} // Challenge method that prompts for username / password private async Task<Credential> ChallengeUI(CredentialRequestInfo cri) { try { string username = "******"; string password = (cri.ServiceUri.Contains("USA_secure_user1")) ? "user1" : "pass.word1"; loginPanel.DataContext = new LoginInfo(cri, username, password); _loginTCS = new TaskCompletionSource<Credential>(loginPanel.DataContext); loginPanel.Visibility = Visibility.Visible; return await _loginTCS.Task; } finally { LoginFlyout.Hide(); } }
// ChallengeHandler function that will be called whenever access to a secured resource is attempted. private async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // IOAuthAuthorizeHandler will challenge the user for OAuth credentials. credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri); } catch (TaskCanceledException) { return(credential); } catch (Exception) { // Exception will be reported in calling function. throw; } return(credential); }
private async Task <bool> EnsureLoggedInAsync() { bool loggedIn = false; try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo challengeRequest = new CredentialRequestInfo { // Use the OAuth implicit grant flow GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }, // Indicate the url (portal) to authenticate with (ArcGIS Online) ServiceUri = new Uri(ServerUrl) }; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler Credential cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); loggedIn = cred != null; } catch (System.OperationCanceledException) { // Login was canceled // .. ignore, user can still search public maps without logging in } catch (Exception ex) { // Login failure AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Login Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } return(loggedIn); }
/// <summary> /// Sign in to Portal /// </summary> private async void signInButton_Click(object sender, RoutedEventArgs e) { signInButton.IsEnabled = false; try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo challengeRequest = new CredentialRequestInfo(); // Use the OAuth implicit grant flow challengeRequest.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with (ArcGIS Online) challengeRequest.ServiceUri = new Uri(ArcGISOnlineUrl); // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler var cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); // Save credential AuthenticationManager.Current.AddCredential(cred); // creat a portal var currentPortal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl)); // show portal info MessageBox.Show(currentPortal.User.FullName); signOutButton.IsEnabled = true; } catch (Exception ex) { // Report error MessageBox.Show("Error while signing in: " + ex.Message); signInButton.IsEnabled = true; } }
// Handle the OnLoginEntered event from the login UI // LoginEventArgs contains the username, password, and domain that were entered private void LoginInfoEntered(object sender, LoginEventArgs e) { // Make sure the task completion source has all the information needed if (_loginTaskCompletionSrc == null || _loginTaskCompletionSrc.Task == null || _loginTaskCompletionSrc.Task.AsyncState == null) { return; } try { // Get the associated CredentialRequestInfo (will need the URI of the service being accessed) CredentialRequestInfo requestInfo = _loginTaskCompletionSrc.Task.AsyncState as CredentialRequestInfo; // Create a new network credential using the values entered by the user var netCred = new System.Net.NetworkCredential(e.Username, e.Password, e.Domain); // Create a new ArcGIS network credential to hold the network credential and service URI var arcgisCred = new ArcGISNetworkCredential { Credentials = netCred, ServiceUri = requestInfo.ServiceUri }; // Set the task completion source result with the ArcGIS network credential // AuthenticationManager is waiting for this result and will add it to its Credentials collection _loginTaskCompletionSrc.TrySetResult(arcgisCred); } catch (Exception ex) { // Unable to create credential, set the exception on the task completion source _loginTaskCompletionSrc.TrySetException(ex); } finally { // Dismiss the login controls Navigation.PopToRootAsync(); } }
// Challenge method should prompt for portal oauth username / password if necessary public static async Task <Credential> Challenge(CredentialRequestInfo arg) { // Register Portal Server if necessary var serverInfo = IdentityManager.Current.FindServerInfo(MainPage.GetUrl()); if (IdentityManager.Current.Credentials.Count() == 0) // || */serverInfo == null) { serverInfo = new ServerInfo() { ServerUri = MainPage.GetUrl(), TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode, OAuthClientInfo = new OAuthClientInfo() { ClientId = CLIENT_ID, RedirectUri = REDIRECT_URI } }; IdentityManager.Current.RegisterServer(serverInfo); } //if(IdentityManager.Current.Credentials.) return(await IdentityManager.Current.GenerateCredentialAsync(MainPage.GetUrl())); }
/// <summary> /// Initializes UI and login task with credential request info. /// </summary> private async Task<Credential> GetCredentialUIAsync(CredentialRequestInfo info) { InitalizeLoginPanel(info.ServiceUri); loginTask = new TaskCompletionSource<Credential>(info); string message = null; Credential credential = null; try { credential = await loginTask.Task; } catch (Exception ex) { message = ex.Message; } finally { LoginPanel.Visibility = Visibility.Collapsed; } if (!string.IsNullOrWhiteSpace(message)) MessageBox.Show(message); return credential; }
// Challenge method that checks for service access with known (hard coded) credentials private async Task <Credential> CreateKnownCredentials(CredentialRequestInfo info) { // If this isn't the expected resource, the credential will stay null Credential knownCredential = null; try { // Check the URL of the requested resource if (info.ServiceUri.AbsoluteUri.ToLower().Contains("usa_secure_user1")) { // Username and password is hard-coded for this resource // (Would be better to read them from a secure source) string username = "******"; string password = "******"; // Create a credential for this resource knownCredential = await AuthenticationManager.Current.GenerateCredentialAsync (info.ServiceUri, username, password, info.GenerateTokenOptions); } else { // Another option would be to prompt the user here if the username and password is not known } } catch (Exception ex) { // Report error accessing a secured resource var alertBuilder = new AlertDialog.Builder(this.ApplicationContext); alertBuilder.SetTitle("Credential Error"); alertBuilder.SetMessage("Access to " + info.ServiceUri.AbsoluteUri + " denied. " + ex.Message); alertBuilder.Show(); } // Return the credential return(knownCredential); }
private async void ShowSaveMapDialog(object sender, EventArgs e) { // Create a SaveMapPage page for getting user input for the new web map item var mapInputForm = new ArcGISRuntime.Samples.AuthorEditSaveMap.SaveMapPage(); // Handle the save button click event on the page mapInputForm.OnSaveClicked += SaveMapAsync; // Navigate to the SaveMapPage UI await Navigation.PushAsync(mapInputForm); // Define an OAuth challenge for ArcGIS Online var info = new CredentialRequestInfo { AuthenticationType = AuthenticationType.Token, ServiceUri = new Uri(ArcGISOnlineUrl) }; // Get the credential try { Credential cred = await AuthenticationManager.Current.GetCredentialAsync(info, false); // Add the credential to the AuthenticationManager AuthenticationManager.Current.AddCredential(cred); } catch (System.Threading.Tasks.TaskCanceledException ex) { // Handle situation where the user closes the login window return; } catch (System.OperationCanceledException ex) { // Handle situation where the user presses 'cancel' in the login UI return; } catch (Exception ex) { // Handle all other exceptions related to canceled login return; } }
private async Task <bool> EnsureLoggedInAsync() { bool loggedIn = false; try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com). CredentialRequestInfo challengeRequest = new CredentialRequestInfo { // Use the OAuth implicit grant flow. GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }, // Indicate the URL (portal) to authenticate with (ArcGIS Online). ServiceUri = new Uri(ServerUrl) }; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler. Credential cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); loggedIn = cred != null; } catch (OperationCanceledException) { // Login was canceled. // .. ignore, user can still search public maps without logging in. } catch (Exception ex) { // Login failure. UIAlertView alert = new UIAlertView("Login Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null); alert.Show(); } return(loggedIn); }
// AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential. private Task <Credential> CreateCredentialAsync(CredentialRequestInfo info) { // Ignore token or certificate challenges (needs additional code and UI). if (info.AuthenticationType != AuthenticationType.NetworkCredential) { Console.WriteLine("Skipped authentication for " + info.ServiceUri.Host); return(null); } // See if authentication is already in progress. if (_loginTaskCompletionSrc != null) { return(null); } // Create a new TaskCompletionSource for the login operation. // Passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property. _loginTaskCompletionSrc = new TaskCompletionSource <Credential>(info); // Create a dialog (fragment) with login controls. LoginDialogFragment enterLoginDialog = new LoginDialogFragment(); // Handle the login and the cancel events. enterLoginDialog.OnLoginClicked += LoginClicked; enterLoginDialog.OnLoginCanceled += (s, e) => { _loginTaskCompletionSrc?.TrySetCanceled(); _loginTaskCompletionSrc = null; }; // Begin a transaction to show a UI fragment (the login dialog). FragmentTransaction transax = FragmentManager.BeginTransaction(); enterLoginDialog.Show(transax, "login"); // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button). return(_loginTaskCompletionSrc.Task); }
private async Task <Credential> CreateCertCredential(CredentialRequestInfo info) { // Handle challenges for a secured resource by prompting for a client certificate. Esri.ArcGISRuntime.Security.Credential credential = null; try { // Create an X509 store for reading certificates for the current user. var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); // Open the store in read-only mode. store.Open(OpenFlags.ReadOnly); // Get a list of certificates that are currently valid. X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true); // Prompt the user to select a certificate using the built-in certificate selection UI. var selection = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate", "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection); // Make sure the user chose a certificate. if (selection.Count > 0) { // Create a new CertificateCredential using the chosen certificate. credential = new CertificateCredential(selection[0]) { ServiceUri = new Uri(_serverUrl) }; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } // Return the CertificateCredential for the secured portal. return(await Task.FromResult(credential)); }
// AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential private async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { // Return if authentication is already in process if (_loginTaskCompletionSrc != null && !_loginTaskCompletionSrc.Task.IsCanceled) { return null; } // Create a new TaskCompletionSource for the login operation // (passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property) _loginTaskCompletionSrc = new TaskCompletionSource<Credential>(info); // Provide a title for the login form (show which service needs credentials) #if WINDOWS_UWP // UWP doesn't have ServiceUri.GetLeftPart (could use ServiceUri.AbsoluteUri for all, but why not use a compilation condition?) _loginPage.TitleText = "Login for " + info.ServiceUri.AbsoluteUri; #else _loginPage.TitleText = "Login for " + info.ServiceUri.GetLeftPart(UriPartial.Path); #endif // Show the login controls on the UI thread // OnLoginInfoEntered event will return the values entered (username, password, and domain) Device.BeginInvokeOnMainThread(async () => await Navigation.PushAsync(_loginPage)); // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button) return await _loginTaskCompletionSrc.Task; }
/// <inheritdoc cref="Esri.ArcGISRuntime.Security.IChallengeHandler.CreateCredentialAsync(CredentialRequestInfo)" /> public Task <Credential> CreateCredentialAsync(CredentialRequestInfo info) { TaskCompletionSource <Credential> tcs = new TaskCompletionSource <Credential>(); _dispatcher.InvokeAsync(() => { if (info.AuthenticationType == AuthenticationType.Certificate) { var cert = Authentication.CertificateHelper.SelectCertificate(info); tcs.SetResult(cert); } else { var login = CreateWindow(info); login.Closed += (s, e) => { tcs.SetResult((login.Content as SignInForm).Credential); }; login.ShowDialog(); } }); return(tcs.Task); }
// Challenge method should prompt for portal oauth username / password if necessary public static async Task<Credential> Challenge(CredentialRequestInfo arg) { // Register Portal Server if necessary var serverInfo = IdentityManager.Current.FindServerInfo(PORTAL_URL); if (serverInfo == null) { serverInfo = new ServerInfo() { ServerUri = PORTAL_URL, TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode, OAuthClientInfo = new OAuthClientInfo() { ClientId = CLIENT_ID, RedirectUri = REDIRECT_URI } }; IdentityManager.Current.RegisterServer(serverInfo); } // Use portal URL always (we know all layers are owned by arcgis.com) return await IdentityManager.Current.GenerateCredentialAsync(PORTAL_URL); }
/// <inheritdoc /> Task<Credential> IChallengeHandler.CreateCredentialAsync(CredentialRequestInfo info) { TaskCompletionSource<Credential> tcs = new TaskCompletionSource<Credential>(); _dispatcher.InvokeAsync(() => { if (info.AuthenticationType == AuthenticationType.Certificate) { var cert = Authentication.CertificateHelper.SelectCertificate(info); if (cert is null) { tcs.SetException(new System.InvalidOperationException("No certificate was selected.")); } else { tcs.SetResult(cert); } } else { var login = CreateWindow(info); login.Closed += (s, e) => { var credential = (login.Content as SignInForm)?.Credential; if (credential is null) { tcs.SetException(new System.InvalidOperationException(" No credential was provided.")); } else { tcs.SetResult(credential); } }; login.ShowDialog(); } }); return tcs.Task; }
// Challenge method that checks for service access with known (hard coded) credentials private async Task<Credential> CreateKnownCredentials(CredentialRequestInfo info) { // If this isn't the expected resource, the credential will stay null Credential knownCredential = null; try { // Check the URL of the requested resource if (info.ServiceUri.AbsoluteUri.ToLower().Contains("usa_secure_user1")) { // Username and password is hard-coded for this resource // (Would be better to read them from a secure source) string username = "******"; string password = "******"; // Create a credential for this resource knownCredential = await AuthenticationManager.Current.GenerateCredentialAsync (info.ServiceUri, username, password, info.GenerateTokenOptions); } else { // Another option would be to prompt the user here if the username and password is not known } } catch (Exception ex) { // Report error accessing a secured resource var messageDlg = new MessageDialog("Access to " + info.ServiceUri.AbsoluteUri + " denied. " + ex.Message, "Credential Error"); messageDlg.ShowAsync(); } // Return the credential return knownCredential; }
/// <summary> /// Challenge for getting the credential allowing to access to the specified ArcGIS resource. /// </summary> /// <param name="credentialRequestInfo">Information about the ArcGIS resource that needs a credential for getting access to.</param> /// <returns>a Task object with <see cref="Credential"/> upon successful completion. /// Otherwise, the Task.Exception is set.</returns> public virtual Task<Credential> CreateCredentialAsync(CredentialRequestInfo credentialRequestInfo) { if (credentialRequestInfo == null) throw new ArgumentNullException("credentialRequestInfo"); var serverInfo = IdentityManager.Current.FindServerInfo(credentialRequestInfo.ServiceUri); if (credentialRequestInfo.AuthenticationType == AuthenticationType.Certificate) { // Challenge for a certificate return CompatUtility.ExecuteOnUIThread(()=>CreateCertificateCredentialAsync(credentialRequestInfo)); } // Check if we need to use OAuth for login. // In this case we don't have to display the SignInDialog by ourself but we have to go through the OAuth authorization page bool isOauth = false; if (serverInfo != null && credentialRequestInfo.AuthenticationType == AuthenticationType.Token) { if (serverInfo.TokenAuthenticationType != TokenAuthenticationType.ArcGISToken) { isOauth = true; // portal secured by OAuth } else if (!string.IsNullOrEmpty(serverInfo.OwningSystemUri)) { // server federated to OAuth portal? // Check if the portal uses OAuth isOauth = IdentityManager.Current.ServerInfos.Any(s => SameOwningSystem(s, serverInfo) && s.TokenAuthenticationType != TokenAuthenticationType.ArcGISToken); } } if (isOauth) // OAuth case --> call GenerateCredentialAsync (that will throw an exception if the OAuthAuthorize component is not set) return CreateOAuthCredentialAsync(credentialRequestInfo); // Display the sign in dialog and create a credential return SignInDialogCreateCredentialAsync(credentialRequestInfo); }
// Handle the OnLoginEntered event from the login UI. // LoginEventArgs contains the username and password that were entered. private async void LoginEntered(object sender, LoginEventArgs e) { // Make sure the task completion source has all the information needed. if (_loginTaskCompletionSource == null || _loginTaskCompletionSource.Task == null || _loginTaskCompletionSource.Task.AsyncState == null) { return; } try { // Get the associated CredentialRequestInfo (will need the URI of the service being accessed). CredentialRequestInfo requestInfo = _loginTaskCompletionSource.Task.AsyncState as CredentialRequestInfo; // Create a token credential using the provided username and password. TokenCredential userCredentials = await AuthenticationManager.Current.GenerateCredentialAsync (requestInfo.ServiceUri, e.Username, e.Password, requestInfo.GenerateTokenOptions); // Set the result on the task completion source. _loginTaskCompletionSource.TrySetResult(userCredentials); } catch (Exception ex) { // Unable to create credential, set the exception on the task completion source. _loginTaskCompletionSource.TrySetException(ex); } finally { // Get rid of the login controls. _loginUI.Hide(); _loginUI = null; } }
// Handle the OnLoginEntered event from the login UI // LoginEventArgs contains the username, password, and domain that were entered private async void LoginInfoEntered(object sender, LoginEventArgs e) { // Make sure the task completion source has all the information needed if (_loginTaskCompletionSrc == null || _loginTaskCompletionSrc.Task == null || _loginTaskCompletionSrc.Task.AsyncState == null) { return; } try { // Get the associated CredentialRequestInfo (will need the URI of the service being accessed) CredentialRequestInfo requestInfo = _loginTaskCompletionSrc.Task.AsyncState as CredentialRequestInfo; // Create a token credential using the provided username and password TokenCredential userCredentials = await AuthenticationManager.Current.GenerateCredentialAsync (requestInfo.ServiceUri, e.Username, e.Password, requestInfo.GenerateTokenOptions); // Set the task completion source result with the ArcGIS network credential // AuthenticationManager is waiting for this result and will add it to its Credentials collection _loginTaskCompletionSrc.TrySetResult(userCredentials); } catch (Exception ex) { // Unable to create credential, set the exception on the task completion source _loginTaskCompletionSrc.TrySetException(ex); } finally { // Dismiss the login controls Navigation.PopToRootAsync(); } }
private async void ShowSaveMapDialog(object sender, EventArgs e) { // Create a SaveMapPage page for getting user input for the new web map item var mapInputForm = new ArcGISRuntime.Samples.AuthorEditSaveMap.SaveMapPage(); // Handle the save button click event on the page mapInputForm.OnSaveClicked += SaveMapAsync; // Navigate to the SaveMapPage UI await Navigation.PushAsync(mapInputForm); // Define an OAuth challenge for ArcGIS Online var info = new CredentialRequestInfo { AuthenticationType = AuthenticationType.Token, ServiceUri = new Uri(ArcGISOnlineUrl) }; // Get the credential Credential cred = await AuthenticationManager.Current.GetCredentialAsync(info, false); // Add the credential to the AuthenticationManager AuthenticationManager.Current.AddCredential(cred); }
public async void licence() { // Challenge the user for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo loginInfo = new CredentialRequestInfo(); // Use the OAuth implicit grant flow loginInfo.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit, }; // Indicate the url (portal) to authenticate with (ArcGIS Online) loginInfo.ServiceUri = new Uri("http://www.arcgis.com/sharing/rest"); try { // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler Credential cred = await AuthenticationManager.Current.GetCredentialAsync(loginInfo, false); // Connect to the portal (ArcGIS Online) using the credential ArcGISPortal arcgisPortal = await ArcGISPortal.CreateAsync(loginInfo.ServiceUri, cred); // Get LicenseInfo from the portal LicenseInfo licenseInfo = await arcgisPortal.GetLicenseInfoAsync(); // ... code here to license the app immediately and/or save the license (JSON string) to take the app offline ... // License the app using the license info ArcGISRuntimeEnvironment.SetLicense(licenseInfo); } catch (Exception ex) { Console.WriteLine("Unable to initialize the ArcGIS Runtime with the client ID provided: " + ex.Message); // TODO: handle exceptions } }
private async Task SaveNewMapAsync(Map myMap, string title, string description, string[] tags, RuntimeImage img) { // Challenge the user for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo loginInfo = new CredentialRequestInfo { // Use the OAuth implicit grant flow GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }, // Indicate the url (portal) to authenticate with (ArcGIS Online) ServiceUri = new Uri("https://www.arcgis.com/sharing/rest") }; try { // Get a reference to the (singleton) AuthenticationManager for the app AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler await thisAuthenticationManager.GetCredentialAsync(loginInfo, false); } catch (System.OperationCanceledException) { // user canceled the login throw new Exception("Portal log in was canceled."); } // Get the ArcGIS Online portal (will use credential from login above) ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync(); // Save the current state of the map as a portal item in the user's default folder await myMap.SaveAsAsync(agsOnline, null, title, description, tags, img); }
private async Task <Credential> Challange(CredentialRequestInfo info) { _loginTaskCompletionSource = new TaskCompletionSource <Credential>(); // Get the login info from the task completion source. var loginEntry = _loginTaskCompletionSource.Task.AsyncState; try { TokenCredential tokenCredentials = await AuthenticationManager.Current.GenerateCredentialAsync( new Uri("https://traffic.arcgis.com/arcgis/rest/services/World/Traffic/MapServer"), "YOUR USERNAME", "YOUR PASSWORD" ); _loginTaskCompletionSource.TrySetResult(tokenCredentials); } catch (Exception ex) { MessageBox.Show(ex.Message); } return(await _loginTaskCompletionSource.Task); }
// Challenge method should prompt for portal oauth username / password if necessary public static async Task <Credential> Challenge(CredentialRequestInfo arg) { // Register Portal Server if necessary var serverInfo = IdentityManager.Current.FindServerInfo(PORTAL_URL); if (serverInfo == null) { serverInfo = new ServerInfo() { ServerUri = PORTAL_URL, TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode, OAuthClientInfo = new OAuthClientInfo() { ClientId = CLIENT_ID, RedirectUri = REDIRECT_URI } }; IdentityManager.Current.RegisterServer(serverInfo); } // Use portal URL always (we know all layers are owned by arcgis.com) return(await IdentityManager.Current.GenerateCredentialAsync(PORTAL_URL)); }
// Challenge method that checks for service access with known (hard coded) credentials. private async Task <Credential> CreateKnownCredentials(CredentialRequestInfo info) { // If this isn't the expected resource, the credential will stay null. Credential knownCredential = null; try { // Check the URL of the requested resource. if (info.ServiceUri.AbsoluteUri.ToLower().Contains("usa_secure_user1")) { // Username and password is hard-coded for this resource (would be better to read this from a secure source). string username = "******"; string password = "******"; // Create a credential for this resource. knownCredential = await AuthenticationManager.Current.GenerateCredentialAsync (info.ServiceUri, username, password, info.GenerateTokenOptions); } else { // Could prompt the user here for other ArcGIS token-secured resources. } } catch (Exception ex) { // Report error accessing a secured resource. var messageDlg = new MessageDialog("Access to " + info.ServiceUri.AbsoluteUri + " denied. " + ex.Message, "Credential Error"); messageDlg.ShowAsync(); } // Return the credential. return(knownCredential); }
private async Task <Credential> CreateKnownCredentials(CredentialRequestInfo info) { Credential credential = null; try { // ArcGIS Online / Portal for ArcGIS へ接続して認証情報を取得 info.ServiceUri = new Uri("https://www.arcgis.com/sharing/rest"); // Username and password is hard-coded for this resource // (Would be better to read them from a secure source) string username = "******"; string password = "******"; // Create a credential for this resource credential = await AuthenticationManager.Current.GenerateCredentialAsync (info.ServiceUri, username, password, info.GenerateTokenOptions); ArcGISPortal arcgisPortal = await ArcGISPortal.CreateAsync(info.ServiceUri, credential); Esri.ArcGISRuntime.LicenseInfo licenseInfo = arcgisPortal.PortalInfo.LicenseInfo; // ArcGIS Runtime にライセンスを設定 Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.SetLicense(licenseInfo); } catch (Exception ex) { DisplayAlert("Credential Error", "Access to " + info.ServiceUri.AbsoluteUri + " denied. " + ex.Message, "OK"); } // Return the credential return(credential); }
public static async Task <Credential> CreateCredential(CredentialRequestInfo info) { Credential credential = null; try { credential = new ArcGISNetworkCredential { Credentials = new System.Net.NetworkCredential(ServiceConfig.Username, ServiceConfig.Password), ServiceUri = info.ServiceUri }; } catch (TaskCanceledException) { return(credential); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } return(credential); }
/// <summary> /// Methos to create a new credential given a refresh token exists /// </summary> private async Task <OAuthTokenCredential> CreateCredentialFromRefreshToken(CredentialRequestInfo info) { // set up credential using the refresh token try { var credential = new OAuthTokenCredential() { ServiceUri = info.ServiceUri, OAuthRefreshToken = GetToken(_oAuthRefreshToken), GenerateTokenOptions = info.GenerateTokenOptions }; await credential.RefreshTokenAsync(); return(credential); } catch { // if using the refresh token fails, clear the token BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(null, BroadcastMessageKey.OAuthRefreshToken); } return(null); }
private async Task <bool> EnsureLoggedInAsync() { bool loggedIn = false; try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo challengeRequest = new CredentialRequestInfo(); // Use the OAuth implicit grant flow challengeRequest.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with (ArcGIS Online) challengeRequest.ServiceUri = new Uri(ArcGISOnlineUrl); // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler var cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); loggedIn = cred != null; } catch (OperationCanceledException) { // OAuth login was canceled // .. ignore this, the user can still search public maps } catch (Exception ex) { // Login failure MessageBox.Show("Login failed: " + ex.Message); } return(loggedIn); }
// Activate IdentityManager but don't accept any challenge. // User must use the 'SignIn' button for getting its own maps. private Task <Credential> Challenge(CredentialRequestInfo arg) { return(Task.FromResult <Credential>(null)); }
// ChallengeHandler function for AuthenticationManager, called whenever access to a secured resource is attempted private async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { OAuthTokenCredential credential = null; try { // Create generate token options if necessary if (info.GenerateTokenOptions == null) { info.GenerateTokenOptions = new GenerateTokenOptions(); } // AuthenticationManager will handle challenging the user for credentials credential = await AuthenticationManager.Current.GenerateCredentialAsync ( info.ServiceUri, info.GenerateTokenOptions ) as OAuthTokenCredential; } catch (Exception ex) { // Exception will be reported in calling function throw (ex); } return credential; }
public LoginInfo(CredentialRequestInfo cri) { RequestInfo = cri; ServiceUrl = new Uri(cri.ServiceUri).GetLeftPart(UriPartial.Path); ErrorMessage = string.Empty; AttemptCount = 0; }
private async void LoadSecureMapButtonClicked(object sender, EventArgs e) { // Store messages that describe success or errors connecting to the secured portal and opening the web map var messageBuilder = new System.Text.StringBuilder(); try { // See if a credential exists for this portal in the AuthenticationManager // If a credential is not found, the user will be prompted for login info CredentialRequestInfo info = new CredentialRequestInfo { ServiceUri = new Uri(SecuredPortalUrl), AuthenticationType = AuthenticationType.NetworkCredential }; Credential cred = await AuthenticationManager.Current.GetCredentialAsync(info, false); // Create an instance of the IWA-secured portal ArcGISPortal iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Report a successful connection messageBuilder.AppendLine("Connected to the portal on " + iwaSecuredPortal.Uri.Host); messageBuilder.AppendLine("Version: " + iwaSecuredPortal.CurrentVersion); // Report the username for this connection if (iwaSecuredPortal.CurrentUser != null) { messageBuilder.AppendLine("Connected as: " + iwaSecuredPortal.CurrentUser.UserName); } else { // This shouldn't happen (if the portal is truly secured)! messageBuilder.AppendLine("Connected anonymously"); } // Get the web map (portal item) to display var webMap = await PortalItem.CreateAsync(iwaSecuredPortal, WebMapId); if (webMap != null) { // Create a new map from the portal item and display it in the map view var map = new Map(webMap); MyMapView.Map = map; } } catch (TaskCanceledException) { // Report canceled login messageBuilder.AppendLine("Login was canceled"); } catch (Exception ex) { // Report error messageBuilder.AppendLine("Exception: " + ex.Message); } finally { // Set the task completion source to null so user can attempt another login (if it failed) _loginTaskCompletionSrc = null; // Display the status of the login DisplayAlert("Status", messageBuilder.ToString(), "OK"); } }
private async void LoadSecureMapButtonClicked(object sender, EventArgs e) { // Store messages that describe success or errors connecting to the secured portal and opening the web map var messageBuilder = new System.Text.StringBuilder(); try { // See if a credential exists for this portal in the AuthenticationManager // If a credential is not found, the user will be prompted for login info CredentialRequestInfo info = new CredentialRequestInfo { ServiceUri = new Uri(SecuredPortalUrl), AuthenticationType = AuthenticationType.NetworkCredential }; Credential cred = await AuthenticationManager.Current.GetCredentialAsync(info, false); // Create an instance of the IWA-secured portal ArcGISPortal iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Report a successful connection messageBuilder.AppendLine("Connected to the portal on " + iwaSecuredPortal.Uri.Host); messageBuilder.AppendLine("Version: " + iwaSecuredPortal.CurrentVersion); // Report the username for this connection if (iwaSecuredPortal.CurrentUser != null) { messageBuilder.AppendLine("Connected as: " + iwaSecuredPortal.CurrentUser.UserName); } else { // This shouldn't happen (if the portal is truly secured)! messageBuilder.AppendLine("Connected anonymously"); } // Get the web map (portal item) to display var webMap = await PortalItem.CreateAsync(iwaSecuredPortal, WebMapId); if (webMap != null) { // Create a new map from the portal item and display it in the map view var map = new Map(webMap); MyMapView.Map = map; } } catch (TaskCanceledException) { // Report canceled login messageBuilder.AppendLine("Login was canceled"); } catch (Exception ex) { // Report error messageBuilder.AppendLine("Exception: " + ex.Message); } finally { // Set the task completion source to null so user can attempt another login (if it failed) _loginTaskCompletionSrc = null; // Display the status of the login DisplayAlert("Status", messageBuilder.ToString(),"OK"); } }
/// <summary> /// Forwards credential request info using Dispatcher to enable access to UI elements. /// </summary> private async Task<Credential> GetCredentialAsync(CredentialRequestInfo info) { if (Dispatcher == null) return await GetCredentialUIAsync(info); return await Dispatcher.Invoke(() => GetCredentialUIAsync(info)); }
private async Task<Credential> WaitForCredentialAsync(CredentialRequestInfo credentialRequestInfo) { Debug.Assert(credentialRequestInfo != null); Cancel(); // cancel previous task _tcs = new TaskCompletionSource<Credential>(); CredentialRequestInfo = credentialRequestInfo; // Will update 'IsReady' status //using (credentialRequestInfo.CancellationToken.Register(Cancel, true)); // for any reason, I get a crash if using true as last argument (whatever the callback, WinPhone bug?) using (credentialRequestInfo.CancellationToken.Register(() => { if (_tcs != null) { _tcs.TrySetCanceled(); _tcs = null; } }, false)) { return await _tcs.Task; } }
private async Task<Credential> DoSignInInUIThread(CredentialRequestInfo credentialRequestInfo) { var signInDialog = this; // Create the ContentDialog that contains the SignInDialog var contentDialog = new ContentDialog { SecondaryButtonText = "cancel", PrimaryButtonText = "sign in", FullSizeDesired = true, Content = signInDialog, }; contentDialog.PrimaryButtonClick += ContentDialogOnPrimaryButtonClick; // Bind the Title so the ContentDialog Title is the SignInDialog title (that will be initialized later) contentDialog.SetBinding(ContentDialog.TitleProperty, new Binding { Path = new PropertyPath("Title"), Source = signInDialog }); contentDialog.SetBinding(ContentDialog.IsPrimaryButtonEnabledProperty, new Binding { Path = new PropertyPath("IsReady"), Source = signInDialog }); contentDialog.Closed += ContentDialogOnClosed; // be sure the SignInDialog is deactivated when pressing back button // Show the content dialog var _ = contentDialog.ShowAsync(); // don't await else that would block here // Wait for the creation of the credential Credential crd; try { crd = await signInDialog.WaitForCredentialAsync(credentialRequestInfo); } finally { // Close the content dialog contentDialog.Hide(); } return crd; }
/// <summary> /// Challenge handler leaveraging the SignInDialog in a content dialog. /// </summary> public Task<Credential> CreateCredentialAsync(CredentialRequestInfo credentialRequestInfo) { return CompatUtility.ExecuteOnUIThread(() => DoSignInInUIThread(credentialRequestInfo)); }
} // end DownloadBtn_Click // Download imagery to a local directory private async void DownloadImagery() { DialogResult result = new DialogResult(); FolderBrowserDialog dialog = new FolderBrowserDialog(); // If a local download - get download directory if (imageFileRB.IsChecked == true) { if (imageFileRB.IsChecked == true) { dialog.Description = "Select download directory"; } else { dialog.Description = "Select temporary download directory"; } dialog.UseDescriptionForTitle = true; result = dialog.ShowDialog(); if (result.ToString() == "OK") { downloadDir = dialog.SelectedPath; } // show progress bar adn hide dowload window mainWin.DownloadPanel.Visibility = Visibility.Visible; downloading = true; Hide(); } else { // Seting up the authorization Debug.WriteLine("Get portal authorization"); agolUser.OAuthPortal(); // Get user credentials Debug.WriteLine("Setting credential request parameters"); CredentialRequestInfo loginInfo = new CredentialRequestInfo { // Use the OAuth implicit grant flow GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }, // Indicate the url (portal) to authenticate with (ArcGIS Online) ServiceUri = new Uri(agolUser.serviceUrl) }; Debug.WriteLine("Getting credentials"); try { Debug.WriteLine("In GetUserPortal - Getting AM"); // Get a reference to the (singleton) AuthenticationManager for the app Esri.ArcGISRuntime.Security.AuthenticationManager thisAM = Esri.ArcGISRuntime.Security.AuthenticationManager.Current; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler Debug.WriteLine("Getting credentials"); await thisAM.GetCredentialAsync(loginInfo, false); Debug.WriteLine("Got credentials"); Debug.WriteLine("In GetUserPortal - login service uri " + loginInfo.ServiceUri); } catch (OperationCanceledException) { // user canceled the login throw new Exception("Portal log in was canceled."); } // show progress bar adn hide dowload window mainWin.DownloadPanel.Visibility = Visibility.Visible; downloading = true; Hide(); // Create the portal // Get the ArcGIS Online portal (will use credential from login above) Debug.WriteLine("Creating the portal"); agolUser.portal = await ArcGISPortal.CreateAsync(); Debug.WriteLine("Portal Created"); /* * var t = Task.Run(() => agolUser.GetUserPortal()); * t.Wait(); */ } // Set up the background worker // for fetching the data dataFetcher = new BackgroundWorker(); if (imageFileRB.IsChecked == true) { dataFetcher.DoWork += Worker_FetchFiles; } else { dataFetcher.DoWork += Worker_AGOL_KMZ; } dataFetcher.WorkerReportsProgress = false; dataFetcher.RunWorkerCompleted += FileFetchCompleted; //Start the worker dataFetcher.RunWorkerAsync(); Debug.WriteLine("leaving DownloadImagery"); } // end DownloadImagery
// Base Challenge method that dispatches to the UI thread if necessary private async Task <Credential> Challenge(CredentialRequestInfo cri) { return(await Challenge_KnownCredentials(cri)); }
private Task<Credential> DoSignInInUIThread(CredentialRequestInfo credentialRequestInfo) { // Create the ChildWindow that contains the SignInDialog var signInDialog = this; var childWindow = new Window { ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.CenterOwner, WindowStyle = WindowStyle.ToolWindow, SizeToContent = SizeToContent.WidthAndHeight, ResizeMode = ResizeMode.NoResize, WindowState = WindowState.Normal, Content = signInDialog }; if (Application.Current != null && Application.Current.MainWindow != null) { try { childWindow.Owner = Application.Current.MainWindow; } catch { // May fire an exception when used inside an excel or powerpoint addins } } // Bind the Title so the ChildWindow Title is the SignInDialog title (that will be initialized later) DependencyProperty titleProperty = Window.TitleProperty; var binding = new Binding("Title") { Source = signInDialog }; childWindow.SetBinding(titleProperty, binding); childWindow.Closed += (s, e) => signInDialog.Cancel(); // be sure the SignInDialog is deactivated when closing the childwindow using the X // initialize the task that gets the credential and then close the window var ts = TaskScheduler.FromCurrentSynchronizationContext(); var doSignInTask = signInDialog.WaitForCredentialAsync(credentialRequestInfo).ContinueWith(task => { childWindow.Close(); return task.Result; }, ts); // Show the window childWindow.ShowDialog(); return doSignInTask; }
private async Task<Credential> WaitForCredentialAsync(CredentialRequestInfo credentialRequestInfo) { Debug.Assert(credentialRequestInfo != null); Cancel(); // cancel previous task _tcs = new TaskCompletionSource<Credential>(); UpdateCanCancel(); CredentialRequestInfo = credentialRequestInfo; using (credentialRequestInfo.CancellationToken.Register(Cancel, true)) { return await _tcs.Task; } }
/// <summary> /// ChallengeHandler function that will be called whenever access to a secured resource is attempted /// </summary> private async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info) { // if credentials are already set, return set values foreach (var cred in AuthenticationManager.Current.Credentials) { if (cred.ServiceUri == new Uri(_arcGISOnlineURL)) { return(cred); } } // Create generate token options if necessary if (info.GenerateTokenOptions == null) { info.GenerateTokenOptions = new GenerateTokenOptions { TokenValidity = -1 }; } // if no refresh token, call to generate credentials // otherwise if a refresh token exists, sign user in using the refresh token OAuthTokenCredential credential = null; if (string.IsNullOrEmpty(_oAuthRefreshToken)) { credential = await CreateNewCredential(info); } else { credential = await CreateCredentialFromRefreshToken(info); if (credential == null) { // Wait for the user to acknowledge that they need to sign in try { await UserPromptMessenger.Instance.AwaitConfirmation( messageTitle : Resources.GetString("ExpiredSignInToken_Title"), message : Resources.GetString("ExpiredSignInToken_Message"), isError : false, stackTrace : null, affirmativeActionButtonContent : null, negativeActionButtonContent : null, shouldCancel : true); // Try again, without token credential = await CreateNewCredential(info); } catch (TaskCanceledException) { // Ignore - user pressed cancel. } } } // add credential to the authentication manager singleton instance to be used in the app AuthenticationManager.Current.AddCredential(credential); try { // Create connection to Portal and provide credential var portal = await ArcGISPortal.CreateAsync(new Uri(_arcGISOnlineURL), credential); // set authenticated user local property AuthenticatedUser = portal.User; } catch (Exception ex) { UserPromptMessenger.Instance.RaiseMessageValueChanged( messageTitle: Resources.GetString(name: "SignInUnsuccessful_Title"), message: ex.Message, isError: true, stackTrace: ex.StackTrace); } // Save refresh token if it has changed. Encrypt if necessary if (credential.OAuthRefreshToken != _oAuthRefreshToken) { if (!string.IsNullOrEmpty(credential.OAuthRefreshToken)) { StoreToken(credential.OAuthRefreshToken, credential.UserName); } else { BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(null, BroadcastMessageKey.OAuthRefreshToken); } } return(credential); }