Access services with OAuth 2.0

Learn how to authenticate a user to access a secure ArcGIS service with OAuth 2.0.

access services with oauth 2

In this tutorial, you will build an app that uses named user login credentials to access a secure ArcGIS service using OAuth 2.0.

You can use different authentication methods to access ArcGIS location services. To implement OAuth 2.0, you can use your ArcGIS account to register an application and get a client ID, and then configure your app to redirect users to login with their credentials when the service or content is accessed. This is known as "named user" or ArcGIS identity authentication. If the app uses premium services that consume credits, the app user's account will be charged.

You will implement OAuth 2.0 so users can sign in to ArcGIS to access the ArcGIS World Traffic service.

Prerequisites

Before starting this tutorial, you should:

  • Have an ArcGIS account and an API key to access ArcGIS services. If you don't have an account, sign up for free.
  • Ensure your development environment meets the system requirements.

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

Steps

Configure OAuth 2.0 for your app

Use the ArcGIS Developer dashboard to create an application, generate a client ID, and define a redirect URL to access secure services.

  1. Sign in to your ArcGIS developer account. If you don't already have one, sign-up for free. You need to sign in so you can create an application and get a client ID for authentication.
  2. Click the OAuth 2.0 tab in the ribbon at the top.
  3. Click the New Application button in the upper-left of the page.
  4. In the Create New Application window, provide a Name and an optional Description for your application definition. Then click Create application. When the application is created, Client ID, Client Secret, and Temporary Token values will also be generated.
  5. Click the Add URI button at the bottom of the page to add a redirect URL.
  6. In the Add Allowed URI window, type my-app://auth and click Add.
You'll use the `client ID` and `redirect URL` when implementing OAuth in your app's code.

The client ID uniquely identifies your app on the authenticating server. If the server cannot find an app with the provided client ID, it will not proceed with authentication.

The redirect URL is used to identify a response from the authenticating server when the system returns control back to your app after an OAuth 2.0 login. You can configure several redirect URLs in your application definition and can remove or edit them. It's important to make sure the redirect URL used in your app's code matches a redirect URL configured for the application.

A temporary token can be used to test access to secure resources without having to implement the full OAuth workflow.

The client secret is only needed in some OAuth workflows and will not be used in this tutorial.

Open a Visual Studio solution

  1. To start the tutorial, complete the Display a map tutorial or download and unzip the solution.

  2. Open the .sln file in Visual Studio.

  3. If you downloaded the solution project, set your API key.

    An API Key enables access to services, web maps, and web scenes hosted in ArcGIS Online.

    If necessary, set the API Key.
    1. Go to your developer dashboard to get your API key. For these tutorials, use your default API key. It is scoped to include all of the services demonstrated in the tutorials.

    2. In Visual Studio, in the Solution Explorer, click App.xaml.cs.

    3. In the App class, add an override for the OnStartup() function to set the ApiKey property on ArcGISRuntimeEnvironment.

      App.xaml.cs
      Use dark colors for code blocks
                                              
      Add line.Add line.Add line.Add line.Add line.Add line.Add line.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
          public partial class App : Application
          {
      
              protected override void OnStartup(StartupEventArgs e)
              {
                  base.OnStartup(e);
                  // Note: it is not best practice to store API keys in source code.
                  // The API key is referenced here for the convenience of this tutorial.
                  Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_API_KEY";
              }
      
          }
      }
      

If developing with Visual Studio for Windows, ArcGIS Runtime for .NET provides a set of project templates for each of the supported .NET platforms. These templates provide all of the code needed for a basic Model-View-ViewModel (MVVM) app. You need to install the ArcGIS Runtime for .NET Visual Studio Extension to add the templates to Visual Studio (Windows only). See Install and set up for details.

Update the tutorial name used in the project (optional)

The Visual Studio solution, project, and the namespace for all classes currently use the name DisplayAMap. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.

The tutorial instructions and code use the name AccessServicesWithOAuth for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.

  1. Update the name for the solution and the project.

    • In Visual Studio, in the Solution Explorer, right-click the solution name and choose Rename. Provide the new name for your solution.
    • In the Solution Explorer, right-click the project name and choose Rename. Provide the new name for your project.
  2. Rename the namespace used by classes in the project.

    • In the Solution Explorer, expand the project node.
    • Double-click MapViewModel.cs in the Solution Explorer to open the file.
    • In the MapViewModel class, double-click the namespace name (DisplayAMap) to select it, and then right-click and choose Rename....
    • Provide the new name for the namespace.
    • Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
  3. Build the project.

    • Choose Build > Build solution (or press <F6>).

Add a traffic layer

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 service requires an ArcGIS Online organizational subscription.

ArcGIS World Traffic service data is updated every five minutes to provide traffic speed and traffic incident visualization and identification.

Traffic speeds are displayed as a percentage of free-flow speeds, which is frequently the speed limit or how fast cars tend to travel when unencumbered by other vehicles. The streets are color coded as follows:

  • Green (fast): 85 - 100% of free flow speeds
  • Yellow (moderate): 65 - 85%
  • Orange (slow); 45 - 65%
  • Red (stop and go): 0 - 45%
  1. In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.

    The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view). MapViewModel.cs contains the view model class for the application, called MapViewModel. See the Microsoft documentation for more information about the Model-View-ViewModel pattern.

  2. In the SetupMap() function, update the line that sets the Map property for the view model to instead store the map in a variable.

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Change lineChange line
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void SetupMap()
            {
    
                // Create a new map with a 'topographic vector' basemap.
                var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    
            }
    
    Expand
  3. Create an ArcGISMapImageLayer to display the traffic service and add it to the map's collection of data layers (operational layers).

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void SetupMap()
            {
    
                // Create a new map with a 'topographic vector' basemap.
                var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    
                // 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);
    
            }
    
    Expand
  4. Set the view model's Map property. Data binding handles displaying the map in the view.

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void SetupMap()
            {
    
                // Create a new map with a 'topographic vector' basemap.
                var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    
                // 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;
    
            }
    
    Expand
  5. Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You should see a map with the topographic basemap layer centered on the Santa Monica Mountains in California. The traffic layer doesn't appear because it requires authentication with ArcGIS Online.

Handle layer load errors

If a map attempts to load a layer based on a secured service without the required authentication, the layer is not added to the map. No exception is raised and unless you handle it in your code, the user may never know that the secured resource is missing from the map.

You will handle load status change events for the traffic layer and report an error message if the layer fails to load.

  1. In the SetupMap() function, after the line that creates the traffic layer, add the following line of code to handle the layer's load status changed event. You will create the code for this handler in another step.

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void SetupMap()
            {
    
                // Create a new map with a 'topographic vector' basemap.
                var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    
                // 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));
    
                // Handle changes in the traffic layer's load status to check for errors.
                trafficLayer.LoadStatusChanged += TrafficLayer_LoadStatusChanged;
    
                // 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;
    
            }
    
    Expand
  2. Below the SetupMap() function, create the function that handles load status change events for the layer. If the layer fails to load, display an error message to the user.

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void TrafficLayer_LoadStatusChanged(object sender, Esri.ArcGISRuntime.LoadStatusEventArgs e)
            {
                // Report the error message if the traffic layer fails to load.
                if (e.Status == Esri.ArcGISRuntime.LoadStatus.FailedToLoad)
                {
                    var trafficLayer = (ArcGISMapImageLayer)sender;
                    System.Windows.MessageBox.Show(trafficLayer?.LoadError?.Message, "Traffic layer did not load");
                }
            }
    
    Expand
  3. Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You should see the same map display, but this time a message box reports a "Token required" error when the traffic layer fails to load. An access token is an authorization string that provides secure access to content, data, and functionality in ArcGIS location services. To load the traffic service layer, you will use OAuth to get an access token based on ArcGIS Online credentials.

Implement OAuth 2.0 authentication

ArcGIS Runtime provides an API that abstracts some of the details for OAuth 2.0 authentication in your app. You can use classes like AuthenticationManager to request, store, and manage credentials for secure resources.

You will add an authentication helper class that uses AuthenticationManager and encapsulates additional authentication logic.

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

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

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

    AuthenticationHelper.cs
    Use dark colors for code blocksCopy
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    //   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 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 AccessServicesWithOAuth
    {
    
        // A helper class that manages authenticating with a server to access secure resources.
        internal static class AuthenticationHelper
        {
            // Specify the client ID and redirect URL to use for OAuth authentication.
            // Create your OAuth application metadata using the ArcGIS developer dashboard:
            // https://developers.arcgis.com/dashboard/
    
            private const string OAuthClientID = "YOUR_CLIENT_ID";
            private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";
    
            static AuthenticationHelper()
            {
                // Use the OAuthAuthorize class (defined below) to show the login UI.
                AuthenticationManager.Current.OAuthAuthorizeHandler = new OAuthAuthorize();
    
                // Create a new ChallengeHandler that uses a method in this class to challenge for credentials.
                AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(PromptCredentialAsync);
            }
    
            // A function to register a secure server with the AuthenticationManager.
            // Pass in the URL of the server containing secure resources and, optionally, a client ID and
            // redirect URL (if not specified, the values defined above are used).
            public static void RegisterSecureServer(string url,
                                                    string clientID = OAuthClientID,
                                                    string redirectUrl = OAuthRedirectUrl)
            {
                // Define the server URL, authentication type, client ID, and redirect URL.
                ServerInfo portalServerInfo = new ServerInfo(new Uri(url))
                {
                    TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode,
                    OAuthClientInfo = new OAuthClientInfo(clientID, new Uri(redirectUrl))
                };
    
                // Register the server information with the AuthenticationManager.
                AuthenticationManager.Current.RegisterServer(portalServerInfo);
            }
    
            // A function that adds a credential to AuthenticationManager based on a temporary token.
            // This is useful for testing an app with secured services without having to log in.
            public static void ApplyTemporaryToken(string url, string token)
            {
                // Create a new OAuth credential for the specified URL with the token.
                OAuthTokenCredential tempToken = new OAuthTokenCredential(new Uri(url), token);
    
                // Add the credential to the AuthenticationManager.
                AuthenticationManager.Current.AddCredential(tempToken);
            }
    
            // The ChallengeHandler function that is called when access to a secured resource is attempted.
            public static async Task<Credential> PromptCredentialAsync(CredentialRequestInfo info)
            {
                Credential credential = null;
    
                try
                {
                    // Get credentials for the specified server. The OAuthAuthorize class (defined below)
                    // will get the user's credentials (show the login window and handle the response).
                    credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri);
                }
                catch (OperationCanceledException)
                {
                    // Login was cancelled, no need to display an error to the user.
                }
    
                return credential;
            }
    
            #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 login UI provided by the server.
                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 authorization request for the server (provides the login UI).
                private string _authorizeUrl;
    
                // Function to initiate an authorization request. 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)
                {
                    // Don't start an authorization request if one is still in progress.
                    if (_tcs != null && !_tcs.Task.IsCompleted)
                    {
                        throw new Exception("Task in progress");
                    }
    
                    // Create a new TaskCompletionSource to track 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 page, make sure it runs on the UI thread for this app.
                    Dispatcher dispatcher = Application.Current.Dispatcher;
                    if (dispatcher == null || dispatcher.CheckAccess())
                    {
                        // Currently on the UI thread, no need to dispatch.
                        ShowLoginWindow(_authorizeUrl);
                    }
                    else
                    {
                        Action authorizeOnUIAction = () => ShowLoginWindow(_authorizeUrl);
                        dispatcher.BeginInvoke(authorizeOnUIAction);
                    }
    
                    // Return the task associated with the TaskCompletionSource.
                    return _tcs.Task;
                }
    
                // A function to show a login page hosted at the specified Url.
                private void ShowLoginWindow(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 sent 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.
                    _authWindow.Closed += OnWindowClosed;
    
                    // Navigate the browser to the authorization url.
                    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)
                {
                    // If no browser, uri, or an empty url, return.
                    WebBrowser webBrowser = sender as WebBrowser;
                    Uri uri = e.Uri;
                    if (webBrowser == null || uri == null || string.IsNullOrEmpty(uri.AbsoluteUri))
                        return;
    
                    // Check if browser was redirected to the callback URL (succesful authentication).
                    if (uri.AbsoluteUri.StartsWith(_callbackUrl))
                    {
                        e.Cancel = true;
    
                        // Call a function to parse key/value pairs from the response URI.
                        IDictionary<string, string> authResponse = DecodeParameters(uri);
    
                        // Set the result for the task completion source with the dictionary.
                        _tcs.SetResult(authResponse);
    
                        // Close the window.
                        if (_authWindow != null)
                        {
                            _authWindow.Close();
                        }
                    }
                }
    
                // A function to parse key/value pairs from the provided URI.
                private static IDictionary<string, string> DecodeParameters(Uri uri)
                {
                    // Get the values from the URI fragment or query string.
                    string responseInfo = "";
                    if (!string.IsNullOrEmpty(uri.Fragment))
                    {
                        responseInfo = uri.Fragment.Substring(1);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(uri.Query))
                        {
                            responseInfo = uri.Query.Substring(1);
                        }
                    }
    
                    // Split the strings for each parameter (delimited with '&').
                    Dictionary<string, string> keyValueDictionary = new Dictionary<string, string>();
                    string[] keysAndValues = responseInfo.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
    
                    // Iterate the parameter info and split into key/value pairs (delimited with '=').
                    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]);
                        }
                        // Add the key and corresponding value to the dictionary.
                        keyValueDictionary.Add(key, value);
                    }
    
                    // Return the dictionary of string keys/values.
                    return keyValueDictionary;
                }
            }
    
            #endregion OAuth handler
    
        }
    }
    
  4. Add your values for client ID (OAuthClientID) and redirect URL (OAuthRedirectUrl ). These were created with your OAuth application metadata in an earlier step and are unique to your application.

    AuthenticationHelper.cs
    Use dark colors for code blocks
                                                                                                                                                                                                                                                                                      
    Change lineChange line
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
        // A helper class that manages authenticating with a server to access secure resources.
        internal static class AuthenticationHelper
        {
            // Specify the client ID and redirect URL to use for OAuth authentication.
            // Create your OAuth application metadata using the ArcGIS developer dashboard:
            // https://developers.arcgis.com/dashboard/
    
            private const string OAuthClientID = "YOUR_CLIENT_ID";
            private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";
    

The AuthenticationHelper class is now set up to handle OAuth authentication in your app. This class is generic enough that you can use it in any app, as long as valid client ID and redirect URL values are provided.

The last step is to use AuthenticationHelper to register one or more server URLs with AuthenticationManager to authenticate the user for secure resources from those servers.

Register ArcGIS Online for OAuth authentication

Registering a server with AuthenticationManager ensures that the user will be authenticated for any secured resources hosted on that server. The server is registered using its URL and the type of authentication it requires (one of the token authentication types supported for ArcGIS). For OAuth authentication, you must also provide required OAuth metadata, such as the client ID and redirect URL.

  1. In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.

  2. In the SetupMap() function, add a line of code that uses AuthenticationHelper to register ArcGIS Online for authentication.

    MapViewModel.cs
    Expand
    Use dark colors for code blocks
                                                                                         
    Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
            private void SetupMap()
            {
    
                // Add the ArcGIS Online URL to the authentication helper.
                AuthenticationHelper.RegisterSecureServer("https://www.arcgis.com/sharing/rest");
    
                // Create a new map with a 'topographic vector' basemap.
                var trafficMap = new Map(BasemapStyle.ArcGISTopographic);
    
                // 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));
    
                // Handle changes in the traffic layer's load status to check for errors.
                trafficLayer.LoadStatusChanged += TrafficLayer_LoadStatusChanged;
    
                // 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;
    
            }
    
    Expand
  3. Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You should again see a map with the topographic basemap layer centered on the Santa Monica Mountains in California. You will be prompted for an ArcGIS Online username and password. Once you authenticate successfully with ArcGIS Online, the traffic layer will appear in the map.

ArcGIS World Traffic service layer

Testing apps that require authentication

When you are testing apps that require authentication for one or more services in the map, it can become monotonous to enter your OAuth credentials repeatedly. You can programmatically add authentication for a server using the temporary token provided with your OAuth application metadata. As the name suggests, this token is valid for a limited time, but you can always get a fresh token from the developer dashboard.

The AuthenticationHelper has the following function for applying a temporary token.

AuthenticationHelper.cs
Use dark colors for code blocksCopy
                                                                                                                                                                                                                                                                                  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        // A function that adds a credential to AuthenticationManager based on a temporary token.
        // This is useful for testing an app with secured services without having to log in.
        public static void ApplyTemporaryToken(string url, string token)
        {
            // Create a new OAuth credential for the specified URL with the token.
            OAuthTokenCredential tempToken = new OAuthTokenCredential(new Uri(url), token);

            // Add the credential to the AuthenticationManager.
            AuthenticationManager.Current.AddCredential(tempToken);
        }

You can call the function with code such as:

Use dark colors for code blocksCopy
 
1
   AuthenticationHelper.ApplyTemporaryToken("https://www.arcgis.com/sharing/rest", "YOUR_TEMP_TOKEN");

Until the token expires, you can run the app without being challenged to provide your credentials.

Additional resources

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

  • ArcGIS Runtime API 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, Xamarin.Android, Xamarin.iOS, and Xamarin.Forms.
  • Xamarin.Essentials WebAuthenticator: This authenticator helps you initiate browser-based OAuth flows in your Android or iOS apps. This component (and the Essentials library) is being ported to .NET MAUI.
  • Web authentication broker: Use this authentication broker to implement OAuth in your Universal Windows Platform (UWP) apps.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.