Skip to content

[New] Authenticate with token #613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Samples.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@
1C26ED202A8BEC63009B7721 /* FilterFeaturesInSceneView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = 1C26ED152A859525009B7721 /* FilterFeaturesInSceneView.swift */; };
1C293D012DCA7C99000B0822 /* ApplyBlendRendererToHillshadeView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = 1C3891602DC02F1100ADFDDC /* ApplyBlendRendererToHillshadeView.swift */; };
1C293D032DCA7C99000B0822 /* ApplyBlendRendererToHillshadeView.SettingsView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = 1C3892302DC59E5D00ADFDDC /* ApplyBlendRendererToHillshadeView.SettingsView.swift */; };
1C293D502DCEA74C000B0822 /* AuthenticateWithTokenView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C293D4E2DCEA74C000B0822 /* AuthenticateWithTokenView.swift */; };
1C293D512DCEA74C000B0822 /* AuthenticateWithTokenView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = 1C293D4E2DCEA74C000B0822 /* AuthenticateWithTokenView.swift */; };
1C29C9592DBAE50D0074028F /* AddWMTSLayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C29C9532DBAE50D0074028F /* AddWMTSLayerView.swift */; };
1C29C95A2DBAE5770074028F /* AddWMTSLayerView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = 1C29C9532DBAE50D0074028F /* AddWMTSLayerView.swift */; };
1C38915D2DBC36C800ADFDDC /* AddWFSLayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C38915C2DBC36C700ADFDDC /* AddWFSLayerView.swift */; };
Expand Down Expand Up @@ -771,6 +773,7 @@
D7F8C03B2B6056790072BFA7 /* AddFeaturesWithContingentValuesView.swift in Copy Source Code Files */,
D73F066C2B5EE760000B574F /* QueryFeaturesWithArcadeExpressionView.swift in Copy Source Code Files */,
D718A1F02B57602000447087 /* ManageBookmarksView.swift in Copy Source Code Files */,
1C293D512DCEA74C000B0822 /* AuthenticateWithTokenView.swift in Copy Source Code Files */,
D77BC53C2B59A309007B49B6 /* StylePointWithDistanceCompositeSceneSymbolView.swift in Copy Source Code Files */,
D718A1E82B571C9100447087 /* OrbitCameraAroundObjectView.Model.swift in Copy Source Code Files */,
D76929FB2B4F795C0047205E /* OrbitCameraAroundObjectView.swift in Copy Source Code Files */,
Expand Down Expand Up @@ -990,6 +993,7 @@
1C2538522BABACB100337307 /* AugmentRealityToNavigateRouteView.ARSceneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AugmentRealityToNavigateRouteView.ARSceneView.swift; sourceTree = "<group>"; };
1C2538532BABACB100337307 /* AugmentRealityToNavigateRouteView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AugmentRealityToNavigateRouteView.swift; sourceTree = "<group>"; };
1C26ED152A859525009B7721 /* FilterFeaturesInSceneView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterFeaturesInSceneView.swift; sourceTree = "<group>"; };
1C293D4E2DCEA74C000B0822 /* AuthenticateWithTokenView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthenticateWithTokenView.swift; sourceTree = "<group>"; };
1C29C9532DBAE50D0074028F /* AddWMTSLayerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddWMTSLayerView.swift; sourceTree = "<group>"; };
1C38915C2DBC36C700ADFDDC /* AddWFSLayerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddWFSLayerView.swift; sourceTree = "<group>"; };
1C3891602DC02F1100ADFDDC /* ApplyBlendRendererToHillshadeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApplyBlendRendererToHillshadeView.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1412,6 +1416,7 @@
isa = PBXGroup;
children = (
0000FB6D2BBDB17600845921 /* Add 3D tiles layer */,
1C293D4F2DCEA74C000B0822 /* Authenticate with token */,
79D84D0C2A815BED00F45262 /* Add custom dynamic entity data source */,
4D2ADC3E29C26D05003B367F /* Add dynamic entity layer */,
D7848EFD2CBD986400F6F546 /* Add elevation source from raster */,
Expand Down Expand Up @@ -1956,6 +1961,14 @@
path = "Filter features in scene";
sourceTree = "<group>";
};
1C293D4F2DCEA74C000B0822 /* Authenticate with token */ = {
isa = PBXGroup;
children = (
1C293D4E2DCEA74C000B0822 /* AuthenticateWithTokenView.swift */,
);
path = "Authenticate with token";
sourceTree = "<group>";
};
1C29C9622DBAE5D10074028F /* Add WMTS layer */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -3900,6 +3913,7 @@
D757D14B2B6C46E50065F78F /* ListSpatialReferenceTransformationsView.Model.swift in Sources */,
218F35B829C28F4A00502022 /* AuthenticateWithOAuthView.swift in Sources */,
79B7B80A2A1BF8EC00F57C27 /* CreateAndSaveKMLView.swift in Sources */,
1C293D502DCEA74C000B0822 /* AuthenticateWithTokenView.swift in Sources */,
D7C6420C2B4F47E10042B8F7 /* SearchForWebMapView.Model.swift in Sources */,
000D43162B9918420003D3C2 /* ConfigureBasemapStyleParametersView.swift in Sources */,
7573E81C29D6134C00BEED9C /* TraceUtilityNetworkView.Enums.swift in Sources */,
Expand Down
133 changes: 133 additions & 0 deletions Shared/Samples/Authenticate with token/AuthenticateWithTokenView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2025 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.

import ArcGIS
import ArcGISToolkit
import SwiftUI

struct AuthenticateWithTokenView: View {
/// The authenticator to handle authentication challenges.
@StateObject private var authenticator = Authenticator()

/// The loaded map result.
@State private var mapLoadResult: Result<Map, Error>?

/// Creates the map for this sample.
static func makeMap() -> Map {
// The portal to authenticate with named user.
let portal = Portal(url: .portal, connection: .authenticated)

// The portal item to be displayed on the map.
let portalItem = PortalItem(
portal: portal,
id: .trafficMap
)

// Creates map with portal item.
return Map(item: portalItem)
}

var body: some View {
Group {
if let mapLoadResult = mapLoadResult {
switch mapLoadResult {
case .success(let value):
MapView(map: value)
case .failure(let error):
Text("Error loading map: \(errorString(for: error))")
.padding()
}
} else {
ProgressView()
.task {
mapLoadResult = await Result { @MainActor in
let map = Self.makeMap()
try await map.load()
try await map.operationalLayers.first?.load()
return map
}
}
}
}
.authenticator(authenticator)
.onAppear {
// Setting the challenge handlers here in `onAppear` so user is prompted to enter
// credentials every time trying the sample. In real world applications, set challenge
// handlers at the start of the application.

// Sets authenticator as ArcGIS and Network challenge handlers to handle authentication
// challenges.
ArcGISEnvironment.authenticationManager.handleChallenges(using: authenticator)

// In real world applications, uncomment this code to persist credentials in the
// keychain and remove `signOut()` from `onDisappear`.
// setupPersistentCredentialStorage()
}
.onDisappear {
// Resetting the challenge handlers and clearing credentials here in `onDisappear`
// so user is prompted to enter credentials every time trying the sample. In real
// world applications, do these from sign out functionality of the application.

// Resets challenge handlers.
ArcGISEnvironment.authenticationManager.handleChallenges(using: nil)

signOut()
}
}

/// The string describing an error.
/// - Parameter error: The error.
private func errorString(for error: Error) -> String {
if error is CancellationError {
return "User cancelled error"
} else if let error = error as? ArcGISError {
return error.details
} else {
return error.localizedDescription
}
}

/// Signs out from the portal by revoking OAuth tokens and clearing credential stores.
private func signOut() {
Task {
await ArcGISEnvironment.authenticationManager.revokeOAuthTokens()
await ArcGISEnvironment.authenticationManager.clearCredentialStores()
}
}

/// Sets up new ArcGIS and Network credential stores that will be persisted in the keychain.
private func setupPersistentCredentialStorage() {
Task {
try await ArcGISEnvironment.authenticationManager.setupPersistentCredentialStorage(
access: .whenUnlockedThisDeviceOnly,
synchronizesWithiCloud: false
)
}
}
}

private extension URL {
/// The URL of the portal to authenticate.
/// - Note: If you want to use your own portal, provide URL here.
static let portal = URL(string: "https://www.arcgis.com")!
}

private extension PortalItem.ID {
/// The portal item ID of a web map to be displayed on the map.
static var trafficMap: Self { Self("e5039444ef3c48b8a8fdc9227f9be7c1")! }
}

#Preview {
AuthenticateWithTokenView()
}
44 changes: 44 additions & 0 deletions Shared/Samples/Authenticate with token/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Authenticate with token

Access a web map that is secured with ArcGIS token-based authentication.

![Login screen](authenticate-with-token1.png)
![Map view after authentication](authenticate-with-token2.png)

## Use case

Allows you to access a secure service with the convenience and security of ArcGIS token-based authentication. For example, rather than providing a user name and password every time you want to access a secure service, you only provide those creditials initially to obtain a token which then can be used to access secured resources.

## How to use the sample

Once you launch the app, you will be challenged for an ArcGIS Online login to view the protected map service. Enter a user name and password for an ArcGIS Online named user account (such as your ArcGIS for Developers account). If you authenticate successfully, the protected map service will display in the map.

## How it works

1. Create a toolkit component `Authenticator` object.
2. Create a `Portal`.
3. Create a `PortalItem` for the protected web map using the Portal and Item ID of the protected map service.
4. Create a map to display in the MapView using the `PortalItem`.
5. Set the map to display in the `MapView`.
6. Set authenticator object as ArcGIS and Network challenge handlers on authentication manager to handle authentication challenges.

## Relevant API

* AuthenticationManager
* Authenticator
* Map
* MapView
* Portal
* PortalItem

## About the data

The [Traffic web map](https://arcgisruntime.maps.arcgis.com/home/item.html?id=e5039444ef3c48b8a8fdc9227f9be7c1) uses public layers as well as the world traffic (premium content) layer. The world traffic service presents historical and near real-time traffic information for different regions in the world. The data is updated every 5 minutes. This map service requires an ArcGIS Online organizational subscription.

## Additional information

Please note: the username and password are case sensitive for token-based authentication. If the user doesn't have permission to access all the content within the portal item, partial or no content will be returned.

## Tags

authentication, cloud, portal, remember, security
35 changes: 35 additions & 0 deletions Shared/Samples/Authenticate with token/README.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"category": "Cloud and Portal",
"description": "Access a web map that is secured with ArcGIS token-based authentication.",
"ignore": false,
"images": [
"authenticate-with-token1.png",
"authenticate-with-token2.png"
],
"keywords": [
"authentication",
"cloud",
"portal",
"remember",
"security",
"AuthenticationManager",
"Authenticator",
"Map",
"MapView",
"Portal",
"PortalItem"
],
"redirect_from": [],
"relevant_apis": [
"AuthenticationManager",
"Authenticator",
"Map",
"MapView",
"Portal",
"PortalItem"
],
"snippets": [
"AuthenticateWithTokenView.swift"
],
"title": "Authenticate with token"
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading