Android Kotlin openid AppAuth registerForActivityResult not being called

372 Views Asked by At

Using openid AppAuth for login, registerForActivityResult is not called after the successful login, it stops on the login page itself. Expecting : After successful login the web page should close and redirect to calling Activity. Below is sample code :

private lateinit var authorizationService: AuthorizationService
lateinit var config: AuthorizationServiceConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.myLayout)

    authorizationService = AuthorizationService(this)

    binding.btnLogin.setOnClickListener { getAuth() }
}
private fun getAuth() {

    config = AuthorizationServiceConfiguration(
        Uri.parse("{{Domain in URL}}/oauth2/v2.0/authorize"),
            Uri.parse("{{Domain in URL}}/oauth2/v2.0/token?p=B2C_1_SUSI_Test")
    )

    var params: HashMap<String, String> = HashMap()
    params["p"] = "B2C_1_SUSI_Test"

    val request = AuthorizationRequest
        .Builder(config, CLIENT_ID, ResponseTypeValues.CODE, Uri.parse(URL_AUTH_REDIRECT))
        .setScopes(
            "openid", "profile", "email",
                "{{Domain in URL}}/api/app.user.basic" 
        )
        .setRedirectUri(Uri.parse(URL_AUTH_REDIRECT))
        .setAdditionalParameters(params)
        .build()

    val intent = authorizationService.getAuthorizationRequestIntent(request)
    launcher.launch(intent)
}
private val launcher =
    registerForActivityResult(StartActivityForResult()) { result ->

        Log.d("TAG", "registerForActivityResult = $result")

        if (result.resultCode == Activity.RESULT_OK) {
            val ex = AuthorizationException.fromIntent(result.data!!)
            val result = AuthorizationResponse.fromIntent(result.data!!)

            if (ex != null) {
                Log.e("TAG", "registerForActivityResult : Error $ex")
            } else {
                // val secret = ClientSecretBasic(GITHUB_CLIENT_SECRET)
                val token = result?.createTokenExchangeRequest()
                Log.d("TAG", "Token : $token")
            }
        }
    }

Android manifest file as below

<activity
            android:name="net.openid.appauth.RedirectUriReceiverActivity"
            android:exported="true"
            tools:node="replace">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="{{app package}}" />
                <data
                    android:host="{{domain}}"
                    android:path="/oauth2redirect"
                    android:scheme="https" />
                
            </intent-filter>
        </activity>

Please help me out in this.

1

There are 1 best solutions below

0
Aniruddha On

I had the same issue. Here is what worked for me for AppAuth v0.11.1.

  • In the AndroidManifest.xml file: remove the <application android:noHistory="true" /> option if it's there, or just set it to false.

  • In the same file add the following intent filter to the Activity that has the login button:

<intent-filter>
          <action android:name="com.example.yourproject.HANDLE_AUTHORIZATION_RESPONSE"/>
          <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

And that is it. This much configuration was enough to get it working.

Here is my authentication code in the content of a GitHub user authenticaion:

    private val launcher = registerForActivityResult(StartActivityForResult()){
        if (it.resultCode == RESULT_OK) {
            val ex = AuthorizationException.fromIntent(it.data!!)
            val result = AuthorizationResponse.fromIntent(it.data!!)

            if (ex != null){
                Log.e("Github Auth", "launcher: $ex")
            } else {
                val secret = ClientSecretBasic(GITHUB_CLIENT_SECRET)
                val tokenRequest = result?.createTokenExchangeRequest()

                service.performTokenRequest(tokenRequest!!, secret) {res, exception ->
                    if (exception != null){
                        Log.e("Github Auth", "launcher: ${exception.error}" )
                    } else {
                        val token = res?.accessToken
                        viewModel.setToken(token!!)
                        // Move to Github screen
                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
            }
        }
    }

    private fun githubAuth() {
        val redirectUri = Uri.parse("com.example.yourproject://oauth2redirect")
        val authorizeUri = Uri.parse("https://github.com/login/oauth/authorize")
        val tokenUri = Uri.parse("https://github.com/login/oauth/access_token")

        val config = AuthorizationServiceConfiguration(authorizeUri, tokenUri)
        val request = AuthorizationRequest
            .Builder(config, GITHUB_CLIENT_ID, ResponseTypeValues.CODE, redirectUri)
            .setScopes("user repo admin")
            .build()

        val intent = service.getAuthorizationRequestIntent(request)
        launcher.launch(intent)
    }

This article was good help: https://medium.com/androiddevelopers/authenticating-on-android-with-the-appauth-library-7bea226555d5