Select to view content in your preferred language

Authenticate with OAuthApplicationCredential in kotlin android app

495
1
10-18-2023 03:37 AM
FatmaAlzhraa
New Contributor

i have "portalUrl","clientId","clientSecret" and i want  Authenticate with OAuthApplicationCredential in kotlin android app 

and store this credential to view map in portal and access services in server 

0 Kudos
1 Reply
Shubham_Sharma
Esri Contributor

@FatmaAlzhraa You can create a class that implements the ArcGISAuthenticationChallengeHandler interface to handle the authentication.

 

class ArcGISCredentialAuthenticationChallengeHandler(
    val createCredential: suspend () -> Result<ArcGISCredential>
) : ArcGISAuthenticationChallengeHandler {
    override suspend fun handleArcGISAuthenticationChallenge(challenge: ArcGISAuthenticationChallenge): ArcGISAuthenticationChallengeResponse {
        val result = createCredential()
        return result.let {
            if (it.isSuccess) {
                ArcGISAuthenticationChallengeResponse.ContinueWithCredential(it.getOrThrow())
            } else {
                ArcGISAuthenticationChallengeResponse.ContinueAndFailWithError(it.exceptionOrNull()!!)
            }
        }
    }
}
}

 

 

Now you can use this class to set the AuthenticationManager using your client ID and secret:

 

val arcGISChallengeHandler = ArcGISCredentialAuthenticationChallengeHandler {
    OAuthApplicationCredential.create(
        portalUrl = "myPortalURL",
        clientId = "myClientId",
        clientSecret = "myClientSecret",
        tokenExpirationInterval = 0
    )
}
ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = arcGISChallengeHandler

val portal = Portal("myPortalURL", Portal.Connection.Authenticated)
lifecycleScope.launch {
    portal.load().onSuccess {
        println("Success!")
    }.onFailure {
        println("Failed to load portal ${it.printStackTrace()}")
    }
}

 

0 Kudos