Learn how to implement user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more to access a secure ArcGIS service A service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. Learn more with OAuth credentials OAuth credentials are an item that contains parameters required to implement user authentication or app authentication, including a client_id, client_secret, and redirect URIs. They are a type of developer credential. Learn more .

access services with oauth 2

You can use different types of authentication to access secured ArcGIS services A service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. Learn more . To implement OAuth credentials for user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more , you can use your ArcGIS account An ArcGIS account is an identity with a user type and set of privileges that can access specific ArcGIS products, tools, APIs, services, and resources. The main account types that can be used for development are an ArcGIS Location Platform account, ArcGIS Online account, and ArcGIS Enterprise account. ArcGIS Location Platform and ArcGIS Online accounts are also associated with a subscription. Learn more to register an app with your portal ArcGIS portal, also known as a portal, is a website with applications and tools that can be used to create, manage, access, and share geospatial content and data. It supports security and authentication, developer credentials, content and data service management, user and group management, and site administration. A portal can be hosted in Esri's infrastructure or your own infrastructure. Learn more and get a Client ID A Client ID is an identifier associated with an application that assists with client / server OAuth 2.0 authentication for ArcGIS client APIs. Learn more , and then configure your app to redirect users to login with their credentials when the service or content is accessed. This is known as user authentication. If the app uses premium ArcGIS Online ArcGIS Online is a GIS mapping, analytics, data hosting, and content management software as a service (SaaS) product. It includes applications, tools, APIs, and location services for users and developers. It is subscription-based and requires an ArcGIS Online account. Learn more services that consume credits Credits are the currency used by ArcGIS Online Organization accounts to account for data storage and location service consumption. Credits are consumed for specific transactions, such as accessing location services, and types of storage, such as storing features, performing analytics, and using premium content. Learn more , for example, the app user’s account will be charged.

In this tutorial, you will build an app that implements user authentication using OAuth credentials so users can sign in and be authenticated through ArcGIS Online to access the ArcGIS World Traffic service.

Prerequisites

Before starting this tutorial:

Optionally, you may want to install the ArcGIS Maps SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.

Set up authentication

To access the secure ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more used in this tutorial, you will implement user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more . When your app runs, the user will be prompted to authenticate with an ArcGIS Location Platform An ArcGIS Location Platform account, formerly known as an ArcGIS Developer account, is an identity associated with an ArcGIS Location Platform subscription. Learn more or an ArcGIS Online An ArcGIS Online account, also known as an ArcGIS Organization account, is an identity associated with an ArcGIS Online subscription. It can be used to access ArcGIS tools and develop applications with ArcGIS location services for an organization. Learn more account.

Create a new OAuth credential to access the secure resources used in this tutorial.

  1. Complete the Create OAuth credentials for user authentication tutorial.

  2. Copy and paste the ClientID and RedirectURL into a safe location. They will be used in a later step.

All users that access this application need account privileges Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more to access the basemap styles service The ArcGIS Basemap Styles service, also referred to as the Basemap Styles service, is a location service that provides basemap styles and data for the world. It returns styles as Mapbox styles and web maps, and data as vector tiles and/or map tiles. It supports all of the styles in the ArcGIS Basemap style and Open Basemap style family. An ArcGIS Location Platform or ArcGIS Online account is required to use the service. Learn more .

Develop or download

You have two options for completing this tutorial:

  1. Option 1: Develop the code or
  2. Option 2: Download the completed solution

Option 1: Develop the code

Create a new Visual Studio Project

ArcGIS Maps SDK for .NET supports apps for Windows Presentation Framework (WPF), Universal Windows Platform (UWP), Windows UI Library (WinUI), and .NET MAUI. The instructions for this tutorial are specific to creating a WPF .NET project using Visual Studio for Windows.

  1. Start Visual Studio and create a new project.

    • In the Visual Studio start screen, click Create a new project.
    • Choose the WPF Application template for C#. If you don’t see the template listed, you can find it by typing WPF Application into the Search for templates text box.
    • Click Next.
    • Provide required values in the Configure your new project panel:
      • Project name: AccessServicesWithOAuth
      • Location: choose a folder
    • Click Next.
      • Choose the framework: .NET 8.0 (Long Term Support)
    • Click Create to create the project.

Add a reference to the API

  1. Add a reference to the API by installing a NuGet package.

    • In Solution Explorer, right-click Dependencies and choose Manage NuGet Packages.
    • In the NuGet Package Manager window, ensure the selected Package source is nuget.org (upper-right).
    • Select the Browse tab and search for ArcGIS Maps SDK.
    • In the search results, select the appropriate package for your platform. For this tutorial project, choose the Esri.ArcGISRuntime.WPF NuGet package.
    • Confirm the Latest stable version of the package is selected in the Version dropdown.
    • Click Apply.
    • The Preview Changes dialog confirms any package(s) dependencies or conflicts. Review the changes and click OK to continue installing the packages.
    • Review the license information on the License Acceptance dialog and click I Accept to add the package(s) to your project.
    • In the Visual Studio Output window, ensure the packages were successfully installed. If you see an error about the target Windows version, you will fix that in the next step.
    • Close the NuGet Package Manager window.
  2. You may see an error like this in the Visual Studio Error List: The 'Esri.ArcGISRuntime.WPF' nuget package cannot be used to target 'net9.0-windows'. Target 'net9.0-windows10.0.19041.0' or later instead.. If so, follow these steps to address it.

    • In Solution Explorer, right-click the project entry in the tree view and choose Edit Project File.
    • Update the <TargetFramework> element with net9.0-windows10.0.19041.0 (or higher).
    <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
    <UseWPF>true</UseWPF>
    </PropertyGroup>
    • Save the project file and close it.

Create a view model to store app logic

Following the Model-View-ViewModel (MVVM) design pattern, you’ll create view model class to contain properties and methods that your view will bind to.

  1. Add a new class that will define a view model for the project.

    • Click Project > Add Class ….
    • Name the new class MapViewModel.cs.
    • Click Add to create the new class and add it to the project.
    • The new class will open in Visual Studio.
  2. Add required using statements to the view model.

    MapViewModel.cs
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
  3. Implement the INotifyPropertyChanged interface in the MapViewModel class.

    MapViewModel.cs
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
  4. Inside the MapViewModel class, add code to implement the PropertyChanged event.

    MapViewModel.cs
    25 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    2 collapsed lines
    }
  5. Define a new property on the view model called Map that exposes a Map object. When the property is set, call OnPropertyChanged.

    MapViewModel.cs
    25 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private Map? _map;
    public Map? Map
    {
    get { return _map; }
    set
    {
    _map = value;
    OnPropertyChanged();
    }
    }
    }
    2 collapsed lines
    }
  6. Add a function to the MapViewModel class called SetupMap. Start by creating a new map that uses a topographic basemap. Provide an initial viewpoint centered on the Santa Monica Mountains in California.

    MapViewModel.cs
    35 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private Map? _map;
    public Map? Map
    {
    get { return _map; }
    set
    {
    _map = value;
    OnPropertyChanged();
    }
    }
    private void SetupMap()
    {
    // Create a new map with a 'topographic vector' basemap.
    var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    // Set the initial viewpoint around the Santa Monica Mountains in California.
    var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);
    trafficMap.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);
    }
    4 collapsed lines
    }
    }

    You will add a layer to display the ArcGIS World Traffic service, a dynamic map service that presents historical and near real-time traffic information for different regions in the world. This is a secure service and requires an ArcGIS Online organizational subscription.

  7. Create an ArcGISMapImageLayer to display the traffic service and add it to the map’s collection of data layers (operational layers).

    MapViewModel.cs
    51 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public MapViewModel()
    {
    SetupMap();
    }
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private Map? _map;
    public Map? Map
    {
    get { return _map; }
    set
    {
    _map = value;
    OnPropertyChanged();
    }
    }
    private void SetupMap()
    {
    // Create a new map with a 'topographic vector' basemap.
    var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    // Set the initial viewpoint around the Santa Monica Mountains in California.
    var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);
    trafficMap.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);
    // Create a layer to display the ArcGIS World Traffic service.
    var trafficServiceUrl = "https://traffic.arcgis.com/arcgis/rest/services/World/Traffic/MapServer";
    var trafficLayer = new ArcGISMapImageLayer(new Uri(trafficServiceUrl));
    // Add the traffic layer to the map's data layer collection.
    trafficMap.OperationalLayers.Add(trafficLayer);
    }
    4 collapsed lines
    }
    }
  8. Set the view model’s Map property. Data binding handles displaying the map in the view.

    MapViewModel.cs
    46 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private Map? _map;
    public Map? Map
    {
    get { return _map; }
    set
    {
    _map = value;
    OnPropertyChanged();
    }
    }
    private void SetupMap()
    {
    // Create a new map with a 'topographic vector' basemap.
    var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    // Set the initial viewpoint around the Santa Monica Mountains in California.
    var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);
    trafficMap.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);
    // Create a layer to display the ArcGIS World Traffic service.
    var trafficServiceUrl = "https://traffic.arcgis.com/arcgis/rest/services/World/Traffic/MapServer";
    var trafficLayer = new ArcGISMapImageLayer(new Uri(trafficServiceUrl));
    // Add the traffic layer to the map's data layer collection.
    trafficMap.OperationalLayers.Add(trafficLayer);
    // Set the view model Map property with the new map.
    this.Map = trafficMap;
    }
    4 collapsed lines
    }
    }
  9. Add a constructor to the class that calls SetupMap when a new MapViewModel is instantiated.

    MapViewModel.cs
    22 collapsed lines
    // Copyright 2022 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
    //
    // https://www.apache.org/licenses/LICENSE-2.0
    //
    // 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 System;
    using System.Collections.Generic;
    using System.Text;
    using Esri.ArcGISRuntime.Geometry;
    using Esri.ArcGISRuntime.Mapping;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    namespace AccessServicesWithOAuth
    {
    class MapViewModel : INotifyPropertyChanged
    {
    public MapViewModel()
    {
    SetupMap();
    }
    42 collapsed lines
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private Map? _map;
    public Map? Map
    {
    get { return _map; }
    set
    {
    _map = value;
    OnPropertyChanged();
    }
    }
    private void SetupMap()
    {
    // Create a new map with a 'topographic vector' basemap.
    var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    // Set the initial viewpoint around the Santa Monica Mountains in California.
    var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);
    trafficMap.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);
    // Create a layer to display the ArcGIS World Traffic service.
    var trafficServiceUrl = "https://traffic.arcgis.com/arcgis/rest/services/World/Traffic/MapServer";
    var trafficLayer = new ArcGISMapImageLayer(new Uri(trafficServiceUrl));
    // Add the traffic layer to the map's data layer collection.
    trafficMap.OperationalLayers.Add(trafficLayer);
    // Set the view model Map property with the new map.
    this.Map = trafficMap;
    }
    }
    }

Your MapViewModel is complete!

An advantage of using the MVVM design pattern is the ability to reuse code in a view model. Because this API has a nearly-standard API surface across platforms, a view model written for one app typically works on all supported .NET platforms. This view model could be used in a .NET MAUI app, a WinUI app, or a UWP app with little or no modification.

Set developer credentials

To allow your app users to access ArcGIS Location Services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

  1. From the Visual Studio Project menu, choose Add class …. Name the class ArcGISLoginPrompt.cs then click Add. The new class is added to your project and opens in Visual Studio.

  2. Select all the code in the new class and delete it.

  3. Copy all of the code below and paste it into the ArcGISLoginPrompt.cs class in your project.

    ArcGISLoginPrompt.cs
    // Copyright 2021 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: http://www.apache.org/licenses/LICENSE-2.0
    //
    // 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.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 UserAuth
    {
    internal static class ArcGISLoginPrompt
    {
    private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";
    // Specify the Client ID and Redirect URL to use with OAuth authentication.
    // See the instructions here for creating OAuth app settings:
    // https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/
    private const string AppClientId = "YOUR_CLIENT_ID";
    private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";
    public static async Task<bool> EnsureAGOLCredentialAsync()
    {
    bool loggedIn = false;
    try
    {
    // Create the portal, prompting the user to log in if they haven't already.
    var portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl), loginRequired: true);
    // If the user logged in successfully, the portal's User property will be non-null.
    loggedIn = portal.User != null;
    }
    catch (OperationCanceledException)
    {
    // OAuth login was canceled, no need to display error to user.
    }
    catch (Exception ex)
    {
    // Login failure
    MessageBox.Show("Login failed: " + ex.Message);
    }
    return loggedIn;
    }
    public static void RegisterOAuthConfig()
    {
    var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl));
    AuthenticationManager.Current.OAuthUserConfigurations.Add(userConfig);
    AuthenticationManager.Current.OAuthAuthorizeHandler = new OAuthAuthorize();
    }
    #region OAuth handler
    // 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.
    public class OAuthAuthorize : IOAuthAuthorizeHandler
    {
    // Window to contain the OAuth UI.
    private Window? _authWindow;
    // Use a TaskCompletionSource to track the completion of the authorization.
    private TaskCompletionSource<IDictionary<string, string>> _tcs;
    // URL for the authorization callback result (the redirect URI configured for your application).
    private string _callbackUrl = "";
    // URL that handles the OAuth request.
    private string? _authorizeUrl;
    // Function to handle authorization requests, 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 (_tcs != null && !_tcs.Task.IsCompleted)
    throw new Exception("Task in progress");
    _tcs = new TaskCompletionSource<IDictionary<string, string>>();
    // Store the authorization and redirect URLs.
    _authorizeUrl = authorizeUri.AbsoluteUri;
    _callbackUrl = callbackUri.AbsoluteUri;
    // Call a function to show the login controls, make sure it runs on the UI thread for this app.
    Dispatcher dispatcher = Application.Current.Dispatcher;
    if (dispatcher == null || dispatcher.CheckAccess())
    {
    AuthorizeOnUIThread(_authorizeUrl);
    }
    else
    {
    Action authorizeOnUIAction = () => AuthorizeOnUIThread(_authorizeUrl);
    dispatcher.BeginInvoke(authorizeOnUIAction);
    }
    // Return the task associated with the TaskCompletionSource.
    return _tcs.Task;
    }
    // Challenge for OAuth credentials on the UI thread.
    private void AuthorizeOnUIThread(string authorizeUri)
    {
    // Create a WebBrowser control to display the authorize page.
    WebBrowser webBrowser = new WebBrowser();
    // Handle the navigation event for the browser to check for a response to the redirect URL.
    webBrowser.Navigating += WebBrowserOnNavigating;
    // Display the web browser in a new window.
    _authWindow = new Window
    {
    Content = webBrowser,
    Width = 450,
    Height = 450,
    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;
    webBrowser.Navigate(authorizeUri);
    // Display the window.
    _authWindow.ShowDialog();
    }
    // Handle the browser window closing.
    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)
    {
    _authWindow.Owner.Focus();
    }
    // If the task wasn't completed, the user must have closed the window without logging in.
    if (!_tcs.Task.IsCompleted)
    {
    // Set the task completion source exception to indicate a canceled operation.
    _tcs.SetCanceled();
    }
    _authWindow = null;
    }
    // Handle browser navigation (content changing).
    private void WebBrowserOnNavigating(object sender, NavigatingCancelEventArgs e)
    {
    // Check for a response to the callback url.
    const string portalApprovalMarker = "/oauth2/approval";
    WebBrowser? webBrowser = sender as WebBrowser;
    Uri uri = e.Uri;
    // If no browser, uri, or an empty url, return.
    if (webBrowser == null || uri == null || string.IsNullOrEmpty(uri.AbsoluteUri))
    return;
    // Check for redirect.
    bool isRedirected = uri.AbsoluteUri.StartsWith(_callbackUrl) ||
    _callbackUrl.Contains(portalApprovalMarker) && uri.AbsoluteUri.Contains(portalApprovalMarker);
    // Check if browser was redirected to the callback URL. (This indicates succesful authentication.)
    if (isRedirected)
    {
    e.Cancel = true;
    // Call a helper function to decode the response parameters.
    IDictionary<string, string> authResponse = DecodeParameters(uri);
    // Set the result for the task completion source.
    _tcs.SetResult(authResponse);
    // Close the window.
    if (_authWindow != null)
    {
    _authWindow.Close();
    }
    }
    }
    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);
    }
    else
    {
    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;
    }
    }
    #endregion OAuth handler
    }
    }
  4. Add your values for the client ID (AppClientId) and for the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.

    ArcGISLoginPrompt.cs
    internal static class ArcGISLoginPrompt
    {
    private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";
    // Specify the Client ID and Redirect URL to use with OAuth authentication.
    // See the instructions here for creating OAuth app settings:
    // https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/
    private const string AppClientId = "YOUR_CLIENT_ID";
    private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";
  5. In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.

  6. In the App class, add an override for the OnStartup() function to call the SetChallengeHandler() method on your static ArcGISLoginPrompt class.

    App.xaml.cs
    public partial class App : Application
    {
    protected override void OnStartup(StartupEventArgs e)
    {
    base.OnStartup(e);
    // Call a function to set up the AuthenticationManager for OAuth.
    UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();
    }
    }
    }
  7. Save and close the App.xaml.cs file.

Best Practice: The OAuth credentials are stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.

Next, you will set up a view in your project to consume the view model.

Add a map view

A MapView control is used to display a map. You will add a map view to your project UI and use data binding to consume the value of the Map property defined on MapViewModel.

  1. Add required XML namespace and resource declarations.

    MainWindow.xaml
    <Window x:Class="AccessServicesWithOAuth.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AccessServicesWithOAuth"
    xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
    <local:MapViewModel x:Key="MapViewModel" />
    </Window.Resources>
    6 collapsed lines
    <Grid>
    </Grid>
    </Window>
  2. Add a MapView control to MainWindow.xaml and bind it to the MapViewModel.

    MainWindow.xaml
    14 collapsed lines
    <Window x:Class="AccessServicesWithOAuth.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AccessServicesWithOAuth"
    xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
    <local:MapViewModel x:Key="MapViewModel" />
    </Window.Resources>
    <Grid>
    <esri:MapView x:Name="MainMapView"
    Map="{Binding Map, Source={StaticResource MapViewModel}}" />
    </Grid>
    2 collapsed lines
    </Window>

Run the app

Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You will be prompted for a username and password. Once you authenticate successfully, you will see a traffic map centered on the Santa Monica Mountains in California.

ArcGIS World Traffic service layer

Alternatively, you can download the tutorial solution, as follows.

Option 2: Download the solution

  1. Click the Download solution link in the right-hand panel of the page.

  2. Unzip the file to a location on your machine.

  3. Open the .sln file in Visual Studio.

Since the downloaded solution does not contain authentication credentials, you must add the developer credentials that you created in the Set up authentication section.

Set developer credentials in the solution

To allow your app users to access ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

  1. From the Visual Studio Solution explorer window, open the ArcGISLoginPrompt.cs file.

  2. Set your values for the client ID (OAuthClientID) and the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.

    ArcGISLoginPrompt.cs
    internal static class ArcGISLoginPrompt
    {
    private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";
    // Specify the Client ID and Redirect URL to use with OAuth authentication.
    // See the instructions here for creating OAuth app settings:
    // https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/
    private const string AppClientId = "YOUR_CLIENT_ID";
    private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";

Best Practice: The OAuth credentials are stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.

Run the app

Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You will be prompted for a username and password. Once you authenticate successfully, you will see a traffic map centered on the Santa Monica Mountains in California.

ArcGIS World Traffic service layer

Additional resources

If you are implementing OAuth for another .NET platform, you might find some of the following resources helpful.

  • ArcGIS Maps SDK for .NET OAuth sample: The WPF version of this sample uses code similar to code used in this tutorial. The sample is available for other .NET platforms (use the switcher control at the top of the page) to illustrate implementing OAuth for apps targeting WinUI, UWP, and .NET MAUI.
  • Web authentication broker: Use this authentication broker to implement OAuth in your Universal Windows Platform (UWP) apps.