You can manage the authentication process in your application code using the authentication API provided by ArcGIS Maps SDK for Swift. This is the same API used by the Authenticator component, and gives you fine-grained control over the authentication process. When using the API rather than the toolkit, you are responsible for the code that handles authentication details.
The central class in the authentication API is the AuthenticationManager
. This is a static property of the ArcGISEnvironment
.
let authenticationManager = ArcGISEnvironment.authenticationManager
The AuthenticationManager
provides:
- Credential stores for your application to hold ArcGIS and network credentials that are automatically checked when your application attempts to connect to secure resources. These stores can be persisted in a keychain so that the user does not have to sign in again when the application is re-launched. For more information, see Create and store credentials.
- ArcGIS and network challenge handlers that allow your application 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.
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, Identity-Aware Proxy (IAP), 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).
You can catch and respond to these authentication challenges using the ArcGISAuthenticationChallengeHandler
and NetworkAuthenticationChallengeHandler
, respectively.
ArcGIS authentication challenge handler
The ArcGISAuthenticationChallengeHandler
is used to handle authentication challenges from ArcGIS secured resources that require OAuth, Identity-Aware Proxy (IAP), or ArcGIS Token authentication. Handle the challenge by returning the ArcGISAuthenticationChallenge.Disposition
with any of the following options:
continue
- Continue the challenge with the given credential.With Credential( ArcGIS Credential) continue
- The request that issued the authentication challenge will fail with the challenge's error.Without Credential cancel
- The request that issued the authentication challenge will fail withCancellation
.Error
-
Create a class that adopts the
ArcGISAuthenticationChallengeHandler
protocol to handle ArcGIS authentication challenges.Use dark colors for code blocks Copy @MainActor // Creates an ArcGIS authentication challenge handler final class MyArcGISChallengeHandler: ArcGISAuthenticationChallengeHandler { // The OAuth configurations that this challenge handler can work with. let oAuthUserConfigurations: [OAuthUserConfiguration] public init( oAuthUserConfigurations: [OAuthUserConfiguration] = [] ) { self.oAuthUserConfigurations = oAuthUserConfigurations } // Handles 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 theArcGISEnvironment
.Use dark colors for code blocks Copy // Creates the challenge handler with desired OAuth user configurations and set it on the `AuthenticationManager`. let myArcGISChallengeHandler = MyArcGISChallengeHandler(oAuthUserConfigurations: [OAuthUserConfiguration(portalURL: URL(string: "my-portal-URL")!, clientID: "my-client-ID", redirectURL: URL(string: "my-redirect-URL")!)]) 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
with any of the following options:
continue
- Continue the challenge with the given credential.With Credential( Network Credential) continue
- The request that issued the authentication challenge will fail with the challenge's error.Without Credential cancel
- The request that issued the authentication challenge will fail withCancellation
.Error
-
Create a class that adopts the
NetworkAuthenticationChallengeHandler
protocol to handle Network authentication challenges.Use dark colors for code blocks Copy // Creates a Network authentication challenge handler final class MyNetworkChallengeHandler: NetworkAuthenticationChallengeHandler { func handleNetworkAuthenticationChallenge( _ challenge: NetworkAuthenticationChallenge ) async -> NetworkAuthenticationChallenge.Disposition { switch challenge.kind { case .ntlm, .basic, .digest: // Prompts the user for a username and password to create a `NetworkCredential`. // ... return .continueWithCredential(.password(username: "username", password: "password")) case .clientCertificate: // Prompts the user for a client certificate to create a `NetworkCredential`. // ... do { return .continueWithCredential(try .certificate(at: URL(fileURLWithPath: "/pathToCertificate"), password: "password")) } catch { return .continueWithoutCredential } case .serverTrust: // Prompts user to ask if they want to trust an untrusted host. // ... return .continueWithCredential(.serverTrust) case .negotiate: // Rejects the negotiate challenge so next authentication protection // space is tried. return .rejectProtectionSpace @unknown default: return .cancel } } }
-
Set an instance of the class on the
AuthenticationManager.networkAuthenticationChallengeHandler
property of theArcGISEnvironment
.Use dark colors for code blocks Copy // Creates the challenge handler and set it on the `AuthenticationManager`. let myNetworkChallengeHandler = MyNetworkChallengeHandler() ArcGISEnvironment.authenticationManager.networkAuthenticationChallengeHandler = myNetworkChallengeHandler
Create and store credentials
When an authentication challenge is raised, your application can create a credential that is held in the ArcGIS and network credential stores provided by the AuthenticationManager
.
ArcGISCredentialStore
stores ArcGIS credentials.NetworkCredentialStore
stores Network credentials.
These credential stores exist for the lifetime of the application. They ensure that an authentication challenge is only raised if a matching credential does not exist in the store. If you want to avoid prompting users for credentials between application sessions, persist the credential stores in the keychain using the function make
on the authentication manager.
ArcGISEnvironment.authenticationManager.arcGISCredentialStore = try await .makePersistent(
access: .afterFirstUnlockThisDeviceOnly,
synchronizesWithiCloud: true
)
await ArcGISEnvironment.authenticationManager.setNetworkCredentialStore(
try await .makePersistent(access: .afterFirstUnlockThisDeviceOnly, synchronizesWithiCloud: true)
)
During application sign-out, you should revoke all tokens and clear all credentials from the credential stores.
func signOut() async throws {
await revokeOAuthTokens()
await invalidateIAPCredentials()
arcGISCredentialStore.removeAll()
await networkCredentialStore.removeAll()
}
@discardableResult
func revokeOAuthTokens() async -> Bool {
let oAuthUserCredentials = arcGISCredentialStore.credentials.compactMap { $0 as? OAuthUserCredential }
return await withTaskGroup(of: Bool.self, returning: Bool.self) { group in
for credential in oAuthUserCredentials {
group.addTask {
do {
try await credential.revokeToken()
return true
} catch {
return false
}
}
}
return await group.allSatisfy(\.self)
}
}
@discardableResult
func invalidateIAPCredentials() async -> Bool {
let iapCredentials = arcGISCredentialStore.credentials.compactMap {
$0 as? IAPCredential
}
return await withTaskGroup(of: Bool.self, returning: Bool.self) { group in
for credential in iapCredentials {
group.addTask {
return (try? await credential.invalidate()) ?? false
}
}
return await group.allSatisfy(\.self)
}
}