Authenticate with OAuth

View on GitHubSample viewer app

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).

Image of authenticate with OAuth

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.

  1. An Activity which launches a custom tab intent and sets its own result to the redirect URI of the custom tab's result
  2. A ViewModel which launches the above activity when prompted, and when it receives the result, passes it through to the OAuthUserSignIn object
  3. An ArcGISAuthenticationChallengeHandler which prompts the ViewModel to start the sign in process with a URL if it is valid.

Image of a flowchart explaining the OAuth sample

How it works

  1. Create an OAuthConfiguration specifying the portal URL, client ID, and redirect URI.
  2. 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.
  3. Set up ViewModel responsible for launching an OAuth user sign in prompt and retrieving the authorized redirect URI
  4. Crete an ArcGISAuthenticationChallengeHandler that checks if the ArcGISAuthenticationChallenge.requestUrl matches the OAuthUserConfiguration's with canBeUserdForUrl(). If the challenge matches, then create a OAuthUserCredential by invoking the OAuthUserSignInViewModel.promptForOAuthUserSignIn
  5. Set the AuthenticationManager's arcGISAuthenticationChallengeHandler to the ArcGISAuthenticationChallengeHandler created above.
  6. Load a map with premium content requiring authentication to automatically invoke the ArcGISAuthenticationHandler.

Setting up the Manifest.xml:

  1. Set the launch mode for the OAuthUserSignInActivity to route it's intent instance through a call to its onNewIntent() 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"
              ...
  2. 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" />
  3. 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

MainActivity.ktMainActivity.ktOAuthUserSignInActivity.ktOAuthUserSignInViewModel.kt
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* 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()
                    )
                }
            }
    }
}

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