Authenticate with ArcGIS Online (or your own portal) using OAuth2 to access secured resources (such as private web maps or layers). Accessing secured items requires logging in to the portal that hosts them (an ArcGIS Online account, for example).
Use case
Your app may need to access items that are only shared with authorized users. For example, your organization may host private data layers or feature services that are only accessible to verified users. You may also need to take advantage of premium ArcGIS Online services, such as geocoding or routing services, which require a named user login.
How to use the sample
When you run the sample, the app will load a web map which contains premium content. You will be challenged for an ArcGIS Online login to view the private layers. 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 traffic layer will display, otherwise the map will contain only the public basemap layer.
Use of Model View ViewModel (MVVM)
This sample takes advantage of Android's ViewModel
to encapsulate launching the OAuth user sign in prompt, establishing the activity result contract, and verifying the OAuth user's credentials.
- An Activity which launches a custom tab intent and sets its own result to the redirect URI of the custom tab's result
- A ViewModel which launches the above activity when prompted, and when it receives the result, passes it through to the
OAuthUserSignIn
object - An
ArcGISAuthenticationChallengeHandler
which prompts the ViewModel to start the sign in process with a URL if it is valid.
How it works
- Create an
OAuthConfiguration
specifying the portal URL, client ID, and redirect URI. - Create an
OAuthUserSignInActivity
that will launch the sign in page in a Custom Tab and receive & process the redirect intent when completing the Custom Tab prompt. - Set up
ViewModel
responsible for launching an OAuth user sign in prompt and retrieving the authorized redirect URI - Crete an
ArcGISAuthenticationChallengeHandler
that checks if theArcGISAuthenticationChallenge.requestUrl
matches theOAuthUserConfiguration's
withcanBeUserdForUrl()
. If the challenge matches, then create aOAuthUserCredential
by invoking theOAuthUserSignInViewModel.promptForOAuthUserSignIn
- Set the
AuthenticationManager
'sarcGISAuthenticationChallengeHandler
to theArcGISAuthenticationChallengeHandler
created above. - Load a map with premium content requiring authentication to automatically invoke the
ArcGISAuthenticationHandler
.
Setting up the Manifest.xml:
-
Set the launch mode for the
OAuthUserSignInActivity
to route it's intent instance through a call to itsonNewIntent()
method, rather than creating a new instance of the activity. To find out more on setting the launch configuration of an activity, visit the Android docs<activity android:name=".OAuthUserSignInActivity" android:launchMode="singleTop" ...
-
Set the
<intent-filter>
categories tags to be able to launch a custom browser tab.<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" />
-
Set the
data
tag to be able to use the redirect URI to navigate back to the app after prompting for OAuth credentials. To learn more on setting up the data specification to an intent filter, visit the Android docs.<data android:host="auth" android:scheme="my-ags-app" />
Relevant API
- ArcGISAuthenticationChallengeHandler
- ArcGISAuthenticationChallengeResponse
- AuthenticationManager
- OAuthUserConfiguration
- OAuthUserCredential
- OAuthUserSignIn
- PortalItem
Additional information
The sample uses an ActivityResultContract
to get the response from the OAuth user sign in page. This allows for developers to natively navigate back their apps as you can register a callback for an activity result. Android Documentation
The workflow presented in this sample works for all SAML based enterprise (IWA, PKI, Okta, etc.) & social (facebook, google, etc.) identity providers for ArcGIS Online or Portal. For more information, see the topic Set up enterprise logins.
For additional information on using Oauth in your app, see the topic Authenticate with the API in Mobile and Native Named User Login.
For more information on how OAuth works visit OAuth 2.0 with ArcGIS
Tags
authentication, cloud, credential, OAuth, portal, security
Sample Code
/* Copyright 2023 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
*
* http://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.
*
*/
package com.esri.arcgismaps.sample.authenticatewithoauth
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeHandler
import com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeResponse
import com.arcgismaps.httpcore.authentication.OAuthUserConfiguration
import com.arcgismaps.httpcore.authentication.OAuthUserCredential
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.PortalItem
import com.arcgismaps.portal.Portal
import com.esri.arcgismaps.sample.authenticatewithoauth.databinding.ActivityMainBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
// set up data binding for the activity
private val activityMainBinding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_main)
}
private val mapView by lazy {
activityMainBinding.mapView
}
// to view the traffic layer in the portal, you must enter valid ArcGIS Online credentials.
private val portal by lazy {
Portal(getString(R.string.oauth_sample_portal_url), Portal.Connection.Authenticated)
}
private val oAuthConfiguration by lazy {
OAuthUserConfiguration(
portalUrl = portal.url,
clientId = getString(R.string.oauth_sample_client_id),
redirectUrl = getString(R.string.oauth_sample_redirect_uri)
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// initialize the OAuth sign in view model to receive
// the result from the activity result contract
val oAuthUserSignInViewModel = ViewModelProvider(
owner = this,
factory = OAuthUserSignInViewModel.getFactory { activityResultRegistry }
)[OAuthUserSignInViewModel::class.java]
lifecycle.addObserver(oAuthUserSignInViewModel)
lifecycle.addObserver(mapView)
setUpArcGISAuthenticationChallengeHandler(oAuthUserSignInViewModel)
// check if the portal can be loaded
lifecycleScope.launch {
portal.load().onSuccess {
MaterialAlertDialogBuilder(this@MainActivity).setMessage(
"Portal succeeded to load, portal user: ${portal.user?.username}"
).show()
// authentication complete, display PortalItem
mapView.apply {
visibility = View.VISIBLE
map = ArcGISMap(PortalItem(portal.url))
}
}.onFailure { throwable ->
// authentication failed, display error message
activityMainBinding.authFailedMessage.apply {
visibility = View.VISIBLE
text = String.format("Portal failed to load, ${throwable.message}")
}
}
}
}
/**
* Sets up the [ArcGISAuthenticationChallengeHandler] to create an
* [OAuthUserCredential] by launching a browser page to perform a OAuth user
* login prompt using [oAuthUserSignInViewModel]
*/
private fun setUpArcGISAuthenticationChallengeHandler(oAuthUserSignInViewModel: OAuthUserSignInViewModel) {
ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler =
ArcGISAuthenticationChallengeHandler { challenge ->
if (oAuthConfiguration.canBeUsedForUrl(challenge.requestUrl)) {
val oAuthUserCredential =
OAuthUserCredential.create(oAuthConfiguration) { oAuthUserSignIn ->
oAuthUserSignInViewModel.promptForOAuthUserSignIn(oAuthUserSignIn)
}.getOrThrow()
ArcGISAuthenticationChallengeResponse.ContinueWithCredential(oAuthUserCredential)
} else {
ArcGISAuthenticationChallengeResponse.ContinueAndFailWithError(
UnsupportedOperationException()
)
}
}
}
}