Skip to content

Commit 94a19f3

Browse files
Merge pull request #86 from Esri/PaulAllanSturm/authenticateWithToken
"Authenticate with token" sample
2 parents 2c7bf7d + d0ebb06 commit 94a19f3

File tree

6 files changed

+335
-0
lines changed

6 files changed

+335
-0
lines changed

assets/generated_samples_list.json

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,41 @@
275275
"title": "Authenticate with OAuth",
276276
"key": "authenticate_with_oauth"
277277
},
278+
"authenticate_with_token": {
279+
"category": "Cloud and Portal",
280+
"description": "Access a web map that is secured with ArcGIS token-based authentication.",
281+
"ignore": false,
282+
"images": [
283+
"authenticate_with_token.png"
284+
],
285+
"keywords": [
286+
"authentication",
287+
"cloud",
288+
"portal",
289+
"remember",
290+
"security",
291+
"ArcGISAuthenticationChallengeHandler",
292+
"ArcGISMap",
293+
"ArcGISMapView",
294+
"AuthenticationManager",
295+
"Portal",
296+
"PortalItem"
297+
],
298+
"redirect_from": [],
299+
"relevant_apis": [
300+
"ArcGISAuthenticationChallengeHandler",
301+
"ArcGISMap",
302+
"ArcGISMapView",
303+
"AuthenticationManager",
304+
"Portal",
305+
"PortalItem"
306+
],
307+
"snippets": [
308+
"authenticate_with_token_sample.dart"
309+
],
310+
"title": "Authenticate with token",
311+
"key": "authenticate_with_token"
312+
},
278313
"create_mobile_geodatabase": {
279314
"category": "Edit and Manage Data",
280315
"description": "Create and share a mobile geodatabase.",

lib/models/samples_widget_list.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import 'package:arcgis_maps_sdk_flutter_samples/samples/apply_scheduled_updates_
88
import 'package:arcgis_maps_sdk_flutter_samples/samples/apply_simple_renderer_to_feature_layer/apply_simple_renderer_to_feature_layer_sample.dart';
99
import 'package:arcgis_maps_sdk_flutter_samples/samples/apply_unique_value_renderer/apply_unique_value_renderer_sample.dart';
1010
import 'package:arcgis_maps_sdk_flutter_samples/samples/authenticate_with_oauth/authenticate_with_oauth_sample.dart';
11+
import 'package:arcgis_maps_sdk_flutter_samples/samples/authenticate_with_token/authenticate_with_token_sample.dart';
1112
import 'package:arcgis_maps_sdk_flutter_samples/samples/create_mobile_geodatabase/create_mobile_geodatabase_sample.dart';
1213
import 'package:arcgis_maps_sdk_flutter_samples/samples/create_planar_and_geodetic_buffers/create_planar_and_geodetic_buffers_sample.dart';
1314
import 'package:arcgis_maps_sdk_flutter_samples/samples/densify_and_generalize_geometry/densify_and_generalize_geometry_sample.dart';
@@ -55,6 +56,7 @@ const sampleWidgets = <String, Widget>{
5556
ApplySimpleRendererToFeatureLayerSample(),
5657
'apply_unique_value_renderer': ApplyUniqueValueRendererSample(),
5758
'authenticate_with_oauth': AuthenticateWithOAuthSample(),
59+
'authenticate_with_token': AuthenticateWithTokenSample(),
5860
'create_mobile_geodatabase': CreateMobileGeodatabaseSample(),
5961
'create_planar_and_geodetic_buffers': CreatePlanarAndGeodeticBuffersSample(),
6062
'densify_and_generalize_geometry': DensifyAndGeneralizeGeometrySample(),
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Authenticate with token
2+
3+
Access a web map that is secured with ArcGIS token-based authentication.
4+
5+
![Image of authenticate with token](authenticate_with_token.png)
6+
7+
## Use case
8+
9+
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.
10+
11+
## How to use the sample
12+
13+
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 Location Platform account). If you authenticate successfully, the protected map service will display in the map.
14+
15+
## How it works
16+
17+
1. Implement the `ArcGISAuthenticationChallengeHandler` interface to handle the challenges sent by the protected map service.
18+
2. Set the `arcGISAuthenticationChallengeHandler` property on `AuthenticationManager`.
19+
3. Create a `Portal`.
20+
4. Create a `PortalItem` for the protected web map using the `Portal` and Item ID of the protected map service.
21+
5. Create a map to display in the `ArcGISMapView` using the `PortalItem`.
22+
6. Set the map to display in the `ArcGISMapView`.
23+
24+
## Relevant API
25+
26+
* ArcGISAuthenticationChallengeHandler
27+
* ArcGISMap
28+
* ArcGISMapView
29+
* AuthenticationManager
30+
* Portal
31+
* PortalItem
32+
33+
## About the data
34+
35+
The Traffic web map 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 or ArcGIS Location Platform subscription.
36+
37+
## Additional information
38+
39+
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.
40+
41+
## Tags
42+
43+
authentication, cloud, portal, remember, security
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"category": "Cloud and Portal",
3+
"description": "Access a web map that is secured with ArcGIS token-based authentication.",
4+
"ignore": false,
5+
"images": [
6+
"authenticate_with_token.png"
7+
],
8+
"keywords": [
9+
"authentication",
10+
"cloud",
11+
"portal",
12+
"remember",
13+
"security",
14+
"ArcGISAuthenticationChallengeHandler",
15+
"ArcGISMap",
16+
"ArcGISMapView",
17+
"AuthenticationManager",
18+
"Portal",
19+
"PortalItem"
20+
],
21+
"redirect_from": [],
22+
"relevant_apis": [
23+
"ArcGISAuthenticationChallengeHandler",
24+
"ArcGISMap",
25+
"ArcGISMapView",
26+
"AuthenticationManager",
27+
"Portal",
28+
"PortalItem"
29+
],
30+
"snippets": [
31+
"authenticate_with_token_sample.dart"
32+
],
33+
"title": "Authenticate with token"
34+
}
261 KB
Loading
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
//
2+
// Copyright 2024 Esri
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
//
8+
// https://www.apache.org/licenses/LICENSE-2.0
9+
//
10+
// Unless required by applicable law or agreed to in writing, software
11+
// distributed under the License is distributed on an "AS IS" BASIS,
12+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
// See the License for the specific language governing permissions and
14+
// limitations under the License.
15+
//
16+
17+
import 'package:arcgis_maps/arcgis_maps.dart';
18+
import 'package:flutter/material.dart';
19+
20+
import '../../utils/sample_state_support.dart';
21+
22+
class AuthenticateWithTokenSample extends StatefulWidget {
23+
const AuthenticateWithTokenSample({super.key});
24+
25+
@override
26+
State<AuthenticateWithTokenSample> createState() =>
27+
_AuthenticateWithTokenSampleState();
28+
}
29+
30+
class _AuthenticateWithTokenSampleState
31+
extends State<AuthenticateWithTokenSample>
32+
with SampleStateSupport
33+
implements ArcGISAuthenticationChallengeHandler {
34+
// Create a controller for the map view.
35+
final _mapViewController = ArcGISMapView.createController();
36+
37+
@override
38+
void initState() {
39+
super.initState();
40+
41+
// This class implements the ArcGISAuthenticationChallengeHandler interface,
42+
// which allows it to handle authentication challenges via calls to its
43+
// handleArcGISAuthenticationChallenge() method.
44+
ArcGISEnvironment
45+
.authenticationManager.arcGISAuthenticationChallengeHandler = this;
46+
}
47+
48+
@override
49+
void dispose() {
50+
// We do not want to handle authentication challenges outside of this sample,
51+
// so we remove this as the challenge handler.
52+
ArcGISEnvironment
53+
.authenticationManager.arcGISAuthenticationChallengeHandler = null;
54+
55+
// Log out by removing all credentials.
56+
ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll();
57+
58+
super.dispose();
59+
}
60+
61+
@override
62+
Widget build(BuildContext context) {
63+
return Scaffold(
64+
resizeToAvoidBottomInset: false,
65+
// Add a map view to the widget tree and set a controller.
66+
body: ArcGISMapView(
67+
controllerProvider: () => _mapViewController,
68+
onMapViewReady: onMapViewReady,
69+
),
70+
);
71+
}
72+
73+
void onMapViewReady() async {
74+
// Set a portal item map that has a secure layer (traffic).
75+
// Loading the secure layer will trigger an authentication challenge.
76+
_mapViewController.arcGISMap = ArcGISMap.withItem(
77+
PortalItem.withPortalAndItemId(
78+
portal: Portal.arcGISOnline(connection: PortalConnection.authenticated),
79+
itemId: 'e5039444ef3c48b8a8fdc9227f9be7c1',
80+
),
81+
);
82+
}
83+
84+
@override
85+
void handleArcGISAuthenticationChallenge(
86+
ArcGISAuthenticationChallenge challenge) async {
87+
// Show a login dialog to handle the authentication challenge.
88+
await showDialog(
89+
context: context,
90+
builder: (context) => LoginWidget(challenge: challenge),
91+
);
92+
}
93+
}
94+
95+
// A widget that handles an authentication challenge by prompting the user to log in.
96+
class LoginWidget extends StatefulWidget {
97+
final ArcGISAuthenticationChallenge challenge;
98+
99+
const LoginWidget({
100+
super.key,
101+
required this.challenge,
102+
});
103+
104+
@override
105+
State<LoginWidget> createState() => _LoginWidgetState();
106+
}
107+
108+
class _LoginWidgetState extends State<LoginWidget> {
109+
// Controllers for the username and password text fields.
110+
final _usernameController = TextEditingController();
111+
final _passwordController = TextEditingController();
112+
// An error message to display.
113+
String? _error;
114+
// The result: true if the user logged in, false if the user canceled.
115+
bool? _result;
116+
117+
@override
118+
void dispose() {
119+
// If the widget was dismissed without a result, the challenge should fail.
120+
if (_result == null) widget.challenge.continueAndFail();
121+
122+
// Text editing controllers must be disposed.
123+
_usernameController.dispose();
124+
_passwordController.dispose();
125+
126+
super.dispose();
127+
}
128+
129+
@override
130+
Widget build(BuildContext context) {
131+
return Dialog(
132+
child: Padding(
133+
padding: const EdgeInsets.all(20.0),
134+
child: SingleChildScrollView(
135+
child: Column(
136+
mainAxisSize: MainAxisSize.min,
137+
children: [
138+
Text(
139+
'Authentication Required',
140+
style: Theme.of(context).textTheme.titleLarge,
141+
),
142+
// Show the server URL that is requiring authentication.
143+
Text(widget.challenge.requestUri.toString()),
144+
// Text fields for the username and password.
145+
TextField(
146+
controller: _usernameController,
147+
autocorrect: false,
148+
decoration: const InputDecoration(hintText: 'Username'),
149+
),
150+
TextField(
151+
controller: _passwordController,
152+
autocorrect: false,
153+
obscureText: true,
154+
decoration: const InputDecoration(hintText: 'Password'),
155+
),
156+
const SizedBox(height: 10.0),
157+
// Buttons to cancel or log in.
158+
Row(
159+
children: [
160+
ElevatedButton(
161+
onPressed: cancel,
162+
child: const Text('Cancel'),
163+
),
164+
const Spacer(),
165+
ElevatedButton(
166+
onPressed: login,
167+
child: const Text('Login'),
168+
),
169+
],
170+
),
171+
// Display an error message if there is one.
172+
Text(
173+
_error ?? '',
174+
style: const TextStyle(color: Colors.red),
175+
),
176+
],
177+
),
178+
),
179+
),
180+
);
181+
}
182+
183+
void login() async {
184+
setState(() => _error = null);
185+
186+
// Username and password are required.
187+
final username = _usernameController.text;
188+
if (username.isEmpty) {
189+
setState(() => _error = 'Username is required.');
190+
return;
191+
}
192+
final password = _passwordController.text;
193+
if (password.isEmpty) {
194+
setState(() => _error = 'Password is required.');
195+
return;
196+
}
197+
198+
try {
199+
// Attempt to create a credential with the provided username and password.
200+
final credential = await TokenCredential.createWithChallenge(
201+
widget.challenge,
202+
username: username,
203+
password: password,
204+
);
205+
if (!mounted) return;
206+
207+
// If successful, continue with the credential.
208+
widget.challenge.continueWithCredential(credential);
209+
Navigator.of(context).pop(_result = true);
210+
} on ArcGISException catch (e) {
211+
// If there was an error, display the error message.
212+
setState(() => _error = e.message);
213+
}
214+
}
215+
216+
void cancel() {
217+
// If the user cancels, cancel the challenge and dismiss the dialog.
218+
widget.challenge.cancel();
219+
Navigator.of(context).pop(_result = false);
220+
}
221+
}

0 commit comments

Comments
 (0)