Click or drag to resize

AuthenticationManager Class

The Authentication Manager is a singleton class that, when enabled, will manage the user credentials for the following resources:
  • ArcGIS Server resources secured using token-based authentication or using HTTP authentication. Note that only ArcGIS Server versions 10 SP 1 and greater are supported.
  • Secured resources (e.g. web maps).
  • Secured ArcGIS Portal resources.
A credential for accessing to an ArcGIS resource can be preset by using AddCredential(Credential). In this case the credential is used for any requests to the specified resources.

If a request to an ArcGIS resource returns an authorization error, the ChallengeHandler, if not null, is called. This challenge handler can return the credential for accessing to the resource.

If the ChallengeHandler is null or if it doesn't return any credential, the Authorization error is returned to the caller as if the request was executed out of the AuthenticationManager.

Inheritance Hierarchy

Namespace:  Esri.ArcGISRuntime.Security
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.11.0
public sealed class AuthenticationManager

The AuthenticationManager type exposes the following members.

Public propertyCode exampleChallengeHandler
Gets or sets the component that handles the authorization errors in order to get a valid credential object.
Public propertyCredentials
Gets the credentials registered by the Authentication Manager.
Public propertyStatic memberCode exampleCurrent
Gets the single AuthenticationManager instance. This is the only way to get an IdentifyManager instance.
Public propertyCode exampleOAuthAuthorizeHandler
Gets or sets the component sets the component that handles authorization by a resource owner in an oauth workflow.
Public propertyPersistence
Gets or sets the credential persistence.
Public propertyServerInfos
Gets the registered servers.
Public propertyTokenExpirationInterval
Gets or sets the default suggested expiration interval (lifetime) of all tokens.
Public propertyTokenValidity Obsolete.
Gets or sets the default suggested lifetime of the token in minutes. This default value can be overridden for a specific credential by setting TokenValidity.
Public methodCode exampleAddCredential
Adds a new Credential that the AuthenticationManager will use for accessing the resources.
Public methodAddCredentials
Adds a set of new Credentials that the AuthenticationManager will use for accessing resources.
Public methodFindCredential(Uri)
Returns the token credential for the resource identified by the specified url.
Public methodFindCredential(Uri, AuthenticationType)
Returns the credential that supports the specified authentication type for the resource identified by the specified url.
Public methodFindServerInfo
Returns information about the server that is hosting at the specified url.
Public methodCode exampleGenerateCredentialAsync(Uri, GenerateTokenOptions)
Generates a token credential object asynchronously. You need to provide the service URL. This is a helper method typically called by the UI challenging the user.
Public methodCode exampleGenerateCredentialAsync(Uri, String, String, GenerateTokenOptions)
Generates a token credential object asynchronously. You need to provide the service URI, the username and the password. This is a helper method typically called by the UI challenging the user.
Public methodCode exampleGetCredentialAsync
Returns a Credential object of the specified type (credentialRequestInfo.AuthenticationType) that can be used to access the secured resource identified by the input url (credentialRequestInfo.Url). If required, the challenge method will be called and should return the expected credential object. If case of Token AuthenticationType, the user is typically challenged for a username and password which are used to generate a token. This method is typically called internally when a request fails due to an "invalid credentials" error.
Public methodCode exampleRegisterServer
Register secure servers and the token endpoints. The Authentication Manager makes its best guess to determine the location of the secure server and token endpoint so in most cases calling registerServers is not necessary. However if the location of your server or token endpoint is non-standard use this method to register the location. Additionally if portal uses the OAuth authentication, it needs to be registered by this method.
Public methodRemoveAllCredentials
Removes all stored credentials so the challenge handler will be called the next time access to a secured resource is needed.
Public methodRemoveAndRevokeAllCredentialsAsync
Removes all credentials from the cache and revokes tokens if appropriate.
Public methodRemoveAndRevokeCredentialAsync
Removes the given credential from the cache and revokes its token if appropriate.
Public methodRemoveCredential
Removes an existing credential so the challenge handler will be called the next time an access to the resources is needed.
Most generally the ChallengeHandler displays the UI allowing the user to enter the username/password for accessing the resource. Unlike for WinStore application, the API doesn't provide any default UI for Desktop. However, a default challenge handler is set for managing the access though OAuth when the OAuthAuthorizeHandler is set.


Example Name: OAuth

Authenticate with ArcGIS Online (or your own portal) using OAuth2 to access secured resources (such as private web maps or layers).

Code example screen shot.

// Copyright 2017 Esri.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific 
// language governing permissions and limitations under the License.

using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace ArcGISRuntime.WPF.Samples.OAuth
        name: "Authenticate with OAuth",
        category: "Security",
        description: "Authenticate with ArcGIS Online (or your own portal) using OAuth2 to access secured resources (such as private web maps or layers).",
        instructions: "When you run the sample, the app will load a web map which contains premium content. You will be challenged for an ArcGIS Online login to view the private layers. Enter a user name and password for an ArcGIS Online named user account (such as your ArcGIS for Developers account). If you authenticate successfully, the traffic layer will display, otherwise the map will contain only the public basemap layer.",
        tags: new[] { "OAuth", "OAuth2", "authentication", "cloud", "credential", "portal", "security" })]
    public partial class OAuth
        // Constants for OAuth-related values.
        // - The URL of the portal to authenticate with
        private const string ServerUrl = "";
        // - The Client ID for an app registered with the server (the ID below is for a public app created by the ArcGIS Runtime team).
        private const string AppClientId = @"lgAdHkYZYlwwfAhC";
        // - An optional client secret for the app (only needed for the OAuthAuthorizationCode authorization type).
        private const string ClientSecret = "";
        // - A URL for redirecting after a successful authorization (this must be a URL configured with the app).
        private const string OAuthRedirectUrl = @"my-ags-app://auth";
        // - The ID for a web map item hosted on the server (the ID below is for a traffic map of Paris).
        private const string WebMapId = "e5039444ef3c48b8a8fdc9227f9be7c1";

        public OAuth()

            // Call a function to initialize the app and request a web map (with a secured layer).

        private async void Initialize()
                // Set up the AuthenticationManager to use OAuth for secure ArcGIS Online requests.

                // Connect to the portal (ArcGIS Online, for example).
                ArcGISPortal arcgisPortal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl));

                // Get a web map portal item using its ID.
                // If the item contains layers not shared publicly, the user will be challenged for credentials at this point.
                PortalItem portalItem = await PortalItem.CreateAsync(arcgisPortal, WebMapId);

                // Create a new map with the portal item and display it in the map view.
                // If authentication fails, only the public layers are displayed.
                Map myMap = new Map(portalItem);
                MyMapView.Map = myMap;
            catch (Exception e)
                MessageBox.Show(e.ToString(), "Error starting sample");

        private void SetOAuthInfo()
            // Register the server information with the AuthenticationManager, including the OAuth settings.
            ServerInfo serverInfo = new ServerInfo
                ServerUri = new Uri(ServerUrl),
                TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit,
                OAuthClientInfo = new OAuthClientInfo
                    ClientId = AppClientId,
                    RedirectUri = new Uri(OAuthRedirectUrl)

            // If a client secret has been configured, set the authentication type to OAuthAuthorizationCode.
            if (!String.IsNullOrEmpty(ClientSecret))
                // Use OAuthAuthorizationCode if you need a refresh token (and have specified a valid client secret).
                serverInfo.TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode;
                serverInfo.OAuthClientInfo.ClientSecret = ClientSecret;

            // Register this server with AuthenticationManager.

            // Use the custom OAuthAuthorize class (defined in this module) to handle OAuth communication.
            AuthenticationManager.Current.OAuthAuthorizeHandler = new OAuthAuthorize();

            // Use a function in this class to challenge for credentials.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);

        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
            // ChallengeHandler function for AuthenticationManager that will be called whenever a secured resource is accessed.
            Credential credential = null;

                // AuthenticationManager will handle challenging the user for credentials.
                credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri);
            catch (Exception)
                // Exception will be reported in calling function.

            return credential;

    // In a desktop (WPF) app, an IOAuthAuthorizeHandler component is used to handle some of the OAuth details. Specifically, it
    //     implements AuthorizeAsync to show the login UI (generated by the server that hosts secure content) in a web control.
    //     When the user logs in successfully, cancels the login, or closes the window without continuing, the IOAuthAuthorizeHandler
    //     is responsible for obtaining the authorization from the server or raising an OperationCanceledException.
    // Note: a custom IOAuthAuthorizeHandler component is not necessary when using OAuth in an ArcGIS Runtime Universal Windows app.
    //     The UWP AuthenticationManager uses a built-in IOAuthAuthorizeHandler that is based on WebAuthenticationBroker.
    public class OAuthAuthorize : IOAuthAuthorizeHandler
        // A window to contain the OAuth UI.
        private Window _authWindow;

        // A TaskCompletionSource to track the completion of the authorization.
        private TaskCompletionSource<IDictionary<string, string>> _taskCompletionSource;

        // URL for the authorization callback result (the redirect URI configured for the application).
        private string _callbackUrl;

        // URL that handles the OAuth request.
        private string _authorizeUrl;

        // A function to handle authorization requests. It takes the URIs for the secured service, the authorization endpoint, and the redirect URI.
        public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
            // If the TaskCompletionSource.Task has not completed, authorization is in progress.
            if (_taskCompletionSource != null || _authWindow != null)
                // Allow only one authorization process at a time.
                throw new Exception("Authorization is in progress");

            // Store the authorization and redirect URLs.
            _authorizeUrl = authorizeUri.AbsoluteUri;
            _callbackUrl = callbackUri.AbsoluteUri;

            // Create a task completion source to track completion.
            _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();

            // Call a function to show the login controls, make sure it runs on the UI thread.
            Dispatcher dispatcher = Application.Current.Dispatcher;
            if (dispatcher == null || dispatcher.CheckAccess())
                Action authorizeOnUIAction = () => AuthorizeOnUIThread(_authorizeUrl);

            // Return the task associated with the TaskCompletionSource.
            return _taskCompletionSource.Task;

        // A function to challenge for OAuth credentials on the UI thread.
        private void AuthorizeOnUIThread(string authorizeUri)
            // Create a WebBrowser control to display the authorize page.
            WebBrowser authBrowser = new WebBrowser();

            // Handle the navigating event for the browser to check for a response sent to the redirect URL.
            authBrowser.Navigating += WebBrowserOnNavigating;

            // Display the web browser in a new window.
            _authWindow = new Window
                Content = authBrowser,
                Height = 420,
                Width = 350,
                WindowStartupLocation = WindowStartupLocation.CenterOwner

            // Set the app's window as the owner of the browser window (if main window closes, so will the browser).
            if (Application.Current != null && Application.Current.MainWindow != null)
                _authWindow.Owner = Application.Current.MainWindow;

            // Handle the window closed event then navigate to the authorize url.
            _authWindow.Closed += OnWindowClosed;

            // Display the Window.
            if (_authWindow != null)

        private void OnWindowClosed(object sender, EventArgs e)
            // If the browser window closes, return the focus to the main window.
            if (_authWindow != null && _authWindow.Owner != null)

            // If the task wasn't completed, the user must have closed the window without logging in.
            if (_taskCompletionSource != null && !_taskCompletionSource.Task.IsCompleted)
                // Set the task completion to indicate a canceled operation.

            _taskCompletionSource = null;
            _authWindow = null;

        // Handle browser navigation (page content changing).
        private void WebBrowserOnNavigating(object sender, NavigatingCancelEventArgs e)
            // Check for a response to the callback url.
            WebBrowser webBrowser = sender as WebBrowser;
            Uri uri = e.Uri;

            // If no browser, uri, or an empty url return.
            if (webBrowser == null || uri == null || _taskCompletionSource == null || String.IsNullOrEmpty(uri.AbsoluteUri))

            // Check if the new content is from the callback url.
            bool isRedirected = uri.AbsoluteUri.StartsWith(_callbackUrl);

            if (isRedirected)
                // Cancel the event to prevent it from being handled elsewhere.
                e.Cancel = true;

                // Get a local copy of the task completion source.
                TaskCompletionSource<IDictionary<string,string>> tcs = _taskCompletionSource;
                _taskCompletionSource = null;

                // Close the window.
                if (_authWindow != null)

                // Call a helper function to decode the response parameters (which includes the authorization key).
                IDictionary<string,string> authResponse = DecodeParameters(uri);

                // Set the result for the task completion source.

        // A helper function that decodes values from a querystring into a dictionary of keys and values.
        private static IDictionary<string, string> DecodeParameters(Uri uri)
            // Create a dictionary of key value pairs returned in an OAuth authorization response URI query string.
            string answer = "";

            // Get the values from the URI fragment or query string.
            if (!String.IsNullOrEmpty(uri.Fragment))
                answer = uri.Fragment.Substring(1);
                if (!String.IsNullOrEmpty(uri.Query))
                    answer = uri.Query.Substring(1);

            // Parse parameters into key / value pairs.
            Dictionary<string,string> keyValueDictionary = new Dictionary<string, string>();
            string[] keysAndValues = answer.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string kvString in keysAndValues)
                string[] pair = kvString.Split('=');
                string key = pair[0];
                string value = string.Empty;
                if (key.Length > 1)
                    value = Uri.UnescapeDataString(pair[1]);

                keyValueDictionary.Add(key, value);

            // Return the dictionary of string keys/values.
            return keyValueDictionary;
<UserControl x:Class="ArcGISRuntime.WPF.Samples.OAuth.OAuth"
        <esri:MapView x:Name="MyMapView"/>
See Also
Additional Examples
Hyperlink to ExampleDescription
AuthorMapCreate and save a map as an ArcGIS `PortalItem` (i.e. web map).
CertificateAuthenticationWithPkiAccess secured portals using a certificate.
ConfigureSubnetworkTraceGet a server-defined trace configuration for a given tier and modify its traversability scope, add new condition barriers and control what is included in the subnetwork trace result.
DisplaySubtypeFeatureLayerDisplays a composite layer of all the subtype values in a feature class.
DisplayUtilityAssociationsCreate graphics for utility associations in a utility network.
EditBranchVersioningCreate, query and edit a specific server version using service geodatabase.
GenerateOfflineMapTake a web map offline.
GenerateOfflineMapWithOverridesTake a web map offline with additional options for each layer.
IntegratedWindowsAuthConnect to an IWA secured Portal and search for maps.
OAuthAuthenticate with ArcGIS Online (or your own portal) using OAuth2 to access secured resources (such as private web maps or layers).
OfflineBasemapByReferenceUse the `OfflineMapTask` to take a web map offline, but instead of downloading an online basemap, use one which is already on the device.
PerformValveIsolationTraceRun a filtered trace to locate operable features that will isolate an area from the flow of network resources.
SearchPortalMapsFind webmap portal items by using a search term.
TokenSecuredChallengeThis sample demonstrates how to prompt the user for a username and password to authenticate with ArcGIS Server to access an ArcGIS token-secured service. Accessing secured services requires a login that's been defined on the server.
TraceUtilityNetworkDiscover connected features in a utility network using connected, subnetwork, upstream, and downstream traces.