Security and authentication

ArcGIS supports secure access to location services and private data. It ensures that only valid, authorized users and services access protected information. To make authenticated requests to secure resources, you need to implement an authentication method.

An authentication method is a process used to verify the identity of a user or client who attempts to access a secured resource. Your application must present an identity whenever it makes an authenticated request to a secured resource.

This SDK supports the following authentication methods:

  • API key: a permanent token that grants your application access to location services and, with an ArcGIS Developer account, private content (currently in beta). API keys currently only work with ArcGIS Online services.
  • ArcGIS identity (formerly named user)
    • OAuth 2.0: manages ArcGIS authentication and grants a short-lived token generated via OAuth 2.0. This gives your application permission to access ArcGIS secured services authorized to an existing ArcGIS user's account.
    • Tokens: manages ArcGIS authentication and grants a short-lived token generated via Esri's proprietary token-based authentication mechanism. This gives your application permission to access ArcGIS secured services authorized to an existing ArcGIS user's account.
    • Network Credentials: manages network authentication (also known as web-tier authentication) for ArcGIS Enterprise. This gives your application permission to access network secured services authorized to your web-tier's identity store user accounts. Supports HTTP Basic/Digest, Integrated Windows Authentication (IWA), Kerberos, and Public Key Infrastructure (PKI).

For more information, see Security and authentication in the Mapping APIs and location services guide.

API keys

An API key is a permanent access token that grants your public-facing application access to specific, ready-to-use services, and, with an ArcGIS Developer account, private content, items, and limited client referrers (currently in beta).

Use API keys when you want to:

  • Quickly write applications that consume ready-to-use services.
  • Provide access to services without requiring users to sign in with an ArcGIS account.
  • Use an access token that doesn't expire.
Learn more about API keys

Use API keys in your app

An API key can be used to authorize access to specific ArcGIS Online services and resources from your app, as well as to monitor access to those services. An API key is created and managed in the ArcGIS developer dashboard and is tied to your ArcGIS account.

You can set an API key on the ArcGISEnvironment, which will apply the key to all requests your app makes for ArcGIS Online services and resources. You can also set an API key on any class that implements APIKeyResource. When you set an API key for a specific class, it will override any key you may have set on ArcGISEnvironment, enabling more granular usage telemetry and management for ArcGIS Online resources used by your app.

Classes that implement APIKeyResource include:

ArcGIS identity

An ArcGIS identity, also known as a named user login, grants a temporary access token giving your application permission to access the content and services authorized to your application user's ArcGIS Online or ArcGIS Enterprise account. This temporary token is created using the OAuth 2.0 protocol and authorizes your application to act on the user's behalf without revealing their secure password to your application. Any service credits your application consumes are billed to the authenticated user's ArcGIS subscription and, during the authenticated period, your app can access your user's content on their behalf.

Use ArcGIS identity when you want to:

  • Ensure users are signed in and authenticated with their own ArcGIS account.
  • Use your app user's credits to pay for their private data, content, or service transactions.
  • Limit the length of time users can be signed in to your app with a temporary token.
  • Distribute your app through ArcGIS Marketplace.
Learn more about ArcGIS identity

Choose an authentication method

The choice of which type of authentication to implement is primarily dependent upon the resources required by your application. Also consider the strengths and limitations of the API or SDK technology on which your application is built. Your choice of authentication method is also affected by the API with which you build your application. For example, this API provides an AuthenticationManager, with helper methods and patterns to implement ArcGIS identity workflows.

ScenarioSolution
Your app requires access only to ready-to-use services, such as the basemap layer, geocoding, or routing services.API key
Your app allows users to view and edit private data in ArcGIS.ArcGIS identity
Your app uses Esri Leaflet, Mapbox GL JS, or OpenLayers.API key
Your app uses an ArcGIS API.API key or ArcGIS identity

Authentication tool

In this SDK, all aspects of ArcGIS and network authentication have been encapsulated into a single ArcGIS Maps SDK for Swift toolkit component called the Authenticator. This component can handle several types of authentication challenges, such as ArcGIS authentication (token and OAuth), Integrated Windows Authentication (IWA), and Client Certificate (PKI), and provides default actions for login prompts, certificate selection prompts, and server trust prompts. For example, here is the default alert prompting the user for username and password credentials.

Authenticator LoginViewModifier to present a login alert

In the application's App struct, import the ArcGISToolkit, create an instance of the Authenticator, ensure that the application's AuthenticationManager uses it to handle authentication challenges. Set the authenticator view modifier so that a prompt can be displayed if the Authenticator is asked to handle an authentication challenge.

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
import SwiftUI
import ArcGIS
import ArcGISToolkit

@main
struct MainApp: App {

    @ObservedObject var authenticator: Authenticator

    init() {
        // Create an authenticator object.
        authenticator = Authenticator()
        // Set the authenticator to handle authentication challenges.
        ArcGISEnvironment.authenticationManager.handleChallenges(using: authenticator)
    }

    var body: some SwiftUI.Scene {
        WindowGroup {
            ContentView()
                // Set the authenticator view modifier.
                .authenticator(authenticator)
        }
    }
}

You can also configure the Authenticator to persist credentials in the keychain. If the app is restarted, the store of credentials is automatically pre-populated with saved credentials and the user does not have to sign in again.

Use dark colors for code blocksCopy
    
1
2
3
4
try await ArcGISEnvironment.authenticationManager.setupPersistentCredentialStorage(
    access: .whenUnlockedThisDeviceOnly,
    synchronizesWithiCloud: false
)

During application sign-out you should revoke all OAuth user tokens then clear all credentials from the credentials stores.

Use dark colors for code blocksCopy
    
1
2
3
4
// Revokes OAuth refresh and access tokens
await ArcGISEnvironment.authenticationManager.revokeOAuthTokens()
// Clears all ArcGIS and network credentials from their respective stores.
await ArcGISEnvironment.authenticationManager.clearCredentialStores()

To see the Authenticator in action, check out the Authentication Example application and refer to AuthenticationApp.swift in your project.

Authentication manager

If you want to manage the authentication process yourself, use the AuthenticationManager that is available as a static property on the ArcGISEnvironment.

Use dark colors for code blocksCopy
 
1
ArcGISEnvironment.authenticationManager

The AuthenticationManager provides:

  • ArcGIS and network challenge handlers that allow you to respond to the authentication challenges. For example, you can write code to present the user with a login screen and then continue to authenticate with those credentials. For more information, see Handle authentication challenges.
  • The credential stores are available for you to place ArcGIS and network credentials that are automatically checked when your application attempts to connect to secure resources. These stores can also be made persistent in the keychain so that user does not have to sign in again when the application is re-launched. For more information, see Create and store credentials.

Handle authentication challenges

If your application attempts to access a secure resource and there is no matching credential in the credential store, an authentication challenge is raised:

  • ArcGISAuthenticationChallenge is raised if the ArcGIS secured resource requires OAuth or ArcGIS Token authentication.
  • NetworkAuthenticationChallenge is raised if the ArcGIS secured resource requires network credentials, such as Integrated Windows Authentication (IWA) or Public Key Infrastructure (PKI).

Catch and respond to these authentication challenges using the ArcGISAuthenticationChallengeHandler and NetworkAuthenticationChallengeHandler, respectively. These challenge handlers are protocols that you can adopt in any class, structure, or other type.

ArcGIS authentication challenge handler

The ArcGISAuthenticationChallengeHandler is used to handle authentication challenges from ArcGIS secured resources that require OAuth or ArcGIS Token authentication. Handle the challenge by returning the ArcGISAuthenticationChallenge.Disposition. It has the following options:

  • continueWithCredential(ArcGISCredential) - Continue the challenge with the given credential.
  • continueWithoutCredential - The request that issued the authentication challenge will fail with the challenge's error.
  • cancel - The request that issued the authentication challenge will fail with CancellationError.

Create a class adopting the ArcGISAuthenticationChallengeHandler protocol to handle ArcGIS authentication challenges.

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
final class MyArcGISChallengeHandler: ArcGISAuthenticationChallengeHandler {
    /// The OAuth configurations that this challenge handler can work with.
    let oAuthUserConfigurations: [OAuthUserConfiguration]

    public init(
        oAuthUserConfigurations: [OAuthUserConfiguration] = []
    ) {
        self.oAuthUserConfigurations = oAuthUserConfigurations
    }

    /// Handle the challenge to an ArcGIS secured resource that requires OAuth or ArcGIS Token authentication.
    func handleArcGISAuthenticationChallenge(
        _ challenge: ArcGISAuthenticationChallenge
    ) async throws -> ArcGISAuthenticationChallenge.Disposition {
        // If an OAuth user configuration is available for the challenge then create an `OAuthUserCredential`.
        if let configuration = oAuthUserConfigurations.first(where: { $0.canBeUsed(for: challenge.requestURL) }) {
            return .continueWithCredential(
                try await OAuthUserCredential.credential(for: configuration)
            )
        } else {
            // If not, prompt the user for a username and password to create a `TokenCredential`.
            ///...
            return .continueWithCredential(
                try await TokenCredential.credential(for: challenge, username: "username", password: "password")
            )
        }
    }
}

Set an instance of the class on the AuthenticationManager.arcGISAuthenticationChallengeHandler property of the ArcGISEnvironment.

Use dark colors for code blocksCopy
   
1
2
3
/// Create the challenge handler with desired OAuth user configurations and set it on the `AuthenticationManager`.
let myArcGISChallengeHandler = MyArcGISChallengeHandler(oAuthUserConfigurations: [<OAuthUserConfiguration>])
ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = myArcGISChallengeHandler

Network authentication challenge handler

The NetworkAuthenticationChallengeHandler is used to handle authentication challenges from ArcGIS secured resources that require network credentials, such as Integrated Windows Authentication (IWA) or Public Key Infrastructure (PKI). Handle the challenge by returning the NetworkAuthenticationChallenge.Disposition. It has the following options:

  • continueWithCredential(NetworkCredential) - Continue the challenge with the given credential.
  • continueWithoutCredential - The request that issued the authentication challenge will fail with the challenge's error.
  • cancel - The request that issued the authentication challenge will fail with CancellationError.

Create a class adopting the NetworkAuthenticationChallengeHandler protocol to handle Network authentication challenges.

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
final class MyNetworkChallengeHandler: NetworkAuthenticationChallengeHandler {
    func handleNetworkAuthenticationChallenge(
        _ challenge: NetworkAuthenticationChallenge
    ) async -> NetworkAuthenticationChallenge.Disposition {
        switch challenge.kind {
        case .ntlm, .basic, .digest:
            // Prompt the user for a username and password to create a `NetworkCredential`.
            // ...
            return .continueWithCredential(.password(username: "username", password: "password"))
        case .clientCertificate:
            // Prompt the user for a client certificate to create a `NetworkCredential`.
            // ...
            return .continueWithCredential(.certificate(at: <certificate file url>, password: "password"))
        case .serverTrust:
            // Prompt user to ask if they want to trust an untrusted host.
            // ...
            return .continueWithCredential(.serverTrust)
        }
    }
}

Set an instance of the class on the AuthenticationManager.networkAuthenticationChallengeHandler property of the ArcGISEnvironment.

Use dark colors for code blocksCopy
   
1
2
3
// Create the challenge handler and set it on the `AuthenticationManager`.
let myNetworkChallengeHandler = MyNetworkChallengeHandler()
ArcGISEnvironment.authenticationManager.networkAuthenticationChallengeHandler = myNetworkChallengeHandler

Create and store credentials

You can create a credential in the authentication challenge handler when an authentication challenge is raised. See Handle authentication challenges for more information. Store these credentials in ArcGIS and network credential stores provided by the AuthenticationManager.

These credential stores exist for the lifetime of the application and ensure that an authentication challenge is not raised if a matching credential exists in the store. If you want to avoid prompting users for credentials between application sessions, make them persisent in the keychain by setting the store instances created using the function makePersistent(access:synchronizesWithiCloud:) on the authentication manager.

Use dark colors for code blocksCopy
       
1
2
3
4
5
6
7
ArcGISEnvironment.authenticationManager.arcGISCredentialStore = try await .makePersistent(
    access: .afterFirstUnlockThisDeviceOnly,
    synchronizesWithiCloud: <true/false>
)
await ArcGISEnvironment.authenticationManager.setNetworkCredentialStore(
    try await .makePersistent(access: .afterFirstUnlockThisDeviceOnly, synchronizesWithiCloud: <true/false>)
)

During application sign-out you should revoke all OAuth user tokens and then clear all credentials from the credential stores.

Use dark colors for code blocksCopy
       
1
2
3
4
5
6
7
// Iterate through the collection of `OAuthUserCreedential` objects stored in the `ArcGISCredentialStore`.
// Revoke the refresh and access token of each `OAuthUserCredential`.
await oAuthUserCredential.revokeToken()

// Clear all ArcGIS and network credentials from their respective stores.
await ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll()
await ArcGISEnvironment.authenticationManager.networkCredentialStore.removeAll()

ArcGIS credentials

You can access resources secured with ArcGIS identity using the following credential types.

  • OAuthUserCredential - A credential object used to access OAuth token-secured ArcGIS resources.
  • TokenCredential - A credential object used to access token-secured ArcGIS resources.
  • PregeneratedTokenCredential - A credential object used to access token-secured ArcGIS resources using a token that is generated outside of your application.

If you know the services domain/server context, you can create an ArcGIS credential, independent of loading the specific resource and store it in the ArcGISCredentialStore.

OAuthUserCredential

To create an OAuthUserCredential, provide an OAuthUserConfiguration with a valid portal URL, client ID, and redirect URL. This will present the OAuth login page for the user to enter the username and password. Once the OAuthUserCredential is created, you will be able to access token information from the asynchronous tokenInfo property.

Use dark colors for code blocksCopy
       
1
2
3
4
5
6
7
let configuration = OAuthUserConfiguration(
    portalURL: <portal URL>,
    clientID: "<client ID>",
    redirectURL: <redirect URL>
)
let credential = try await OAuthUserCredential.credential(for: configuration)
let tokenInfo = try await credential.tokenInfo

TokenCredential

To create a TokenCredential, provide a secured service URL, valid username, and password. Optionally, you can specify token expiration minutes. Once a TokenCredential is created, you will be able to access token information from the asynchronous tokenInfo property.

Use dark colors for code blocksCopy
       
1
2
3
4
5
6
7
let credential = try await TokenCredential.credential(
    for: <service URL>,
    username: "<username>",
    password: "<password>",
    tokenExpirationMinutes: <minutes>
)
let tokenInfo = try await credential.tokenInfo

PregeneratedTokenCredential

To create a PregeneratedTokenCredential, provide a previously generated short or long-lived access token. Use this credential when the access token is created using the generateToken REST endpoint directly. You must provide the referer if one was used while generating the token.

Use dark colors for code blocksCopy
          
1
2
3
4
5
6
7
8
9
10
let tokenInfo = TokenInfo(
    accessToken: "<access token>",
    expirationDate: <expiration date>,
    isSSLRequired: true
)
let credential = PregeneratedTokenCredential(
    url: <service URL>,
    tokenInfo: tokenInfo,
    referer: "<referer>"
)

Network credentials

You can access resources secured by network authentication using the following credential types.

  • PasswordCredential - A credential object that is used to authenticate HTTP Basic/Digest or Integrated Windows Authentication (IWA) secured resources.
  • CertificateCredential - A credential object that is used to authenticate Client Certificate (PKI) secured resources.
  • NetworkCredential.serverTrust - A network credential that specifies that a server should be trusted.

PasswordCredential

The PasswordCredential is used to authenticate HTTP Basic/Digest, Integrated Windows Authentication (IWA) secured resources. To create a PasswordCredential, use a static function of NetworkCredential with username and a password.

Use dark colors for code blocksCopy
 
1
let credential = NetworkCredential.password(username: "<username>", password: "<password>")

CertificateCredential

A CertificateCredential is used to authenticate Public Key Infrastructure (PKI) secured resources. To create a CertificateCredential, use a static function of NetworkCredential with the URL to a .p12 or .pfx extension certificate file on disk and a password.

Use dark colors for code blocksCopy
 
1
let credential = NetworkCredential.certificate(at: <file url to .p12 or .pfx file> , password: "<password>")

ServerTrust

To trust a development server that uses a self-signed certificate (untrusted host), create a NetworkCredential and specify that the server should be trusted.

Use dark colors for code blocksCopy
 
1
let credential = NetworkCredential.serverTrust

Samples

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