microsoft-authentication-library-for-android icon indicating copy to clipboard operation
microsoft-authentication-library-for-android copied to clipboard

The acquireToken method doesn't work if the app uses "withFragmemt"

Open VolodaUa opened this issue 3 years ago • 26 comments

Details We are going to make b2c authorization in our Android app and we faced with issue with "IMultipleAccountPublicClientApplication.acquireToken" method and fragment.

Smartphone (please complete the following information):

  • Device: Samsun M51
  • Android Version: 12,
  • MSAL Version: 4.0.5

Config { "broker_redirect_uri_registered": false, "client_id" : "****", "authorization_user_agent" : "WEBVIEW", "redirect_uri" : "****", "authorities" : [ { "type": "B2C", "authority_url": "https://schcoad.b2clogin.com/schcoad.onmicrosoft.com/.......", "default": true } ] }

Stacktrace W/MSALLogger: AuthorizationFragment:onCreate | [2022-11-11 13:11:47 - thread_name: main, correlation_id: UNSET - Android 31] No stored state. Unable to handle response W/AuthorizationFragment:onCreate: [2022-11-11 13:11:47 - thread_name: main, correlation_id: UNSET - Android 31] No stored state. Unable to handle response E/MSALLogger: AuthorizationFragment#finish | [2022-11-11 13:11:47 - thread_name: main, correlation_id: UNSET - Android 31] Logged as error to capture 'cause'; Exception occurred when removing ourselves from provided FragmentManager java.lang.IllegalStateException: FragmentManager is already executing transactions at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1636) at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1666) at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:317) at com.microsoft.identity.common.internal.providers.oauth2.AuthorizationFragment.finish(AuthorizationFragment.java:136) at com.microsoft.identity.common.internal.providers.oauth2.AuthorizationFragment.onCreate(AuthorizationFragment.java:94) at com.microsoft.identity.common.internal.providers.oauth2.WebViewAuthorizationFragment.onCreate(WebViewAuthorizationFragment.java:104) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981) at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1758) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701) at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8663) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

To Reproduce

  1. Create the fragment where you would like to have the WebView. As example, in sample app. it can be "MultipleAccountModeFragment" from the sample app.

  2. Set the WebView client for "authorization_user_agent" : "WEBVIEW",

  3. Add the "withFragment" to val parameters: AcquireTokenParameters = AcquireTokenParameters.Builder() .withScopes(AzureUserAuthorizationApi.SCOPES) .startAuthorizationFromActivity(requireActivity())// we are inside fragment .withCallback(b2cAuthenticationCallback) *.withFragment(*this*)// this equals MultipleAccountModeFragment* .withPrompt(Prompt.LOGIN) .build()

  4. call IMultipleAccountPublicClientApplication.acquireToken(parameters)

Expected behavior I would like to have the WebView is run inside the fragment/over MultipleAccountModeFragment. Also, I checked all the provided documentation, samples and I've not found anything how to use "withFragment" method correctly. I kindly ask to document it and it can save a lot of time for developers. Right know it doesn't work.

Actual Behavior The error log message is observed, the spinner is running. 2022-11-11 15 13 24

I found that it by some reasons "savedInstanceState" and "mInstanceState" is null and it closes itself onCreate. AuthorizationFragment.java if (savedInstanceState == null && mInstanceState == null) { Logger.warn(methodTag, "No stored state. Unable to handle response"); **finish();** return; }

VolodaUa avatar Nov 11 '22 13:11 VolodaUa

@negoe Sorry for mentioned you. This issue is critical for our customer future release. Could someone from team to take a look?

VolodaUa avatar Nov 16 '22 12:11 VolodaUa

+1 on this

RileyGB avatar Nov 17 '22 03:11 RileyGB

Looks like the pull request is created but haven't reviewed for long time: https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/1704

VolodaUa avatar Nov 17 '22 12:11 VolodaUa

+1 on this

I found the workaround. Just create the same class in your project with the same package and Java runtime will use your class instead. Please take the fix here: https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/1704

I still see the error about fragment transaction, but it works.

VolodaUa avatar Nov 21 '22 07:11 VolodaUa

+1 on this

I found the workaround. Just create the same class in your project with the same package and Java runtime will use your class instead. Please take the fix here: AzureAD/microsoft-authentication-library-common-for-android#1704

I still see the error about fragment transaction, but it works.

Wow, you're awesome. Thanks for bringing back a workaround. To clarify, you just created src/main/java/com/microsoft/identity/common/internal/providers/oauth2/AndroidAuthorizationStrategy.java in your local source with this fix?

RileyGB avatar Nov 21 '22 23:11 RileyGB

+1 on this. Also need this to be fixed.

reid112 avatar Nov 21 '22 23:11 reid112

+1 on this

I found the workaround. Just create the same class in your project with the same package and Java runtime will use your class instead. Please take the fix here: AzureAD/microsoft-authentication-library-common-for-android#1704 I still see the error about fragment transaction, but it works.

Wow, you're awesome. Thanks for bringing back a workaround. To clarify, you just created src/main/java/com/microsoft/identity/common/internal/providers/oauth2/AndroidAuthorizationStrategy.java in your local source with this fix?

I did this and it worked beautifully. Thanks!

RileyGB avatar Nov 22 '22 04:11 RileyGB

Yes, I just create this file in my project with the same name and package

VolodaUa avatar Nov 22 '22 05:11 VolodaUa

Additional information for assigned person.

Please consider the following sample:

Parent activity:

  • Another fragment:
  • Our Azure fragment. The activity can switch fragments between each other.

If you attach the fragment in the first time, it works with workaround, but it you then switch to "Another fragment" and then back to the Azure, the empty view will be displayed(noting loaded), the error in logs is displayed and it doesn't work.

it cool be to have the working sample and documentation how you should use "withFragment" method correctly.

VolodaUa avatar Nov 22 '22 09:11 VolodaUa

@VolodaUa Thanks for the workaround. But now I having the problem that if I build the app in "release", it's show us the following error:

"Type com.microsoft.identity.common.internal.providers.oauth2.AndroidAuthorizationStrategy is defined multiple times"

Did you find the same problem? Could you solve it?

Thanks

juampiMG avatar Nov 25 '22 13:11 juampiMG

@juampiMG Sorry for late response (( Yes, this one doesn't work in release. Currently, I didn't have enough time to take a look at it and find the fix.

I had ideas to use some plugin to remove/rename the class from the final package, but respecting that the project where I work is huge, I failed this setup.

Currently, I stopped as it fixes only case when you just need to attach the fragment once. Otherwise, the webview stop working and nothing will be displayed.

I strongly suggest considering checking this case during the main fix as it is quite often case.

VolodaUa avatar Nov 30 '22 12:11 VolodaUa

I was able to get this working in release. TLDR; it takes some work.

For my purposes, I wanted to replace both AndroidAuthorizationStrategy.java(this bug) and WebViewAuthorizationFragment.java(I needed access to the webview) with my own implementations.

You may want to get a coffee (or beverage of your choice) before attempting the following:

Removing the necessary files from the library

  • I acquired the AAR for https://github.com/AzureAD/microsoft-authentication-library-common-for-android from my local gradle cache (find an aar in a sub directory of .gradle/caches/modules-2/files-2.1/com.microsoft.identity/common/9.0.0)
  • Since an AAR is just a zip, I renamed its extension to a .zip and unzipped its contents.
  • Within its contents, classes.jar exists. I renamed its extension to a .zip and unzipped its contents.
  • I found and deleted all of the .class files for both AndroidAuthorizationStrategy and WebViewAuthorizationFragment
  • To convert my classes folder to a .jar I ran jar cvf classes.jar classes
  • I took my new classes.jar and put it back in the decompiled aar folder
  • To convert my aar folder to a .aar I ran jar cvf microsoft-common.aar common-9.0.0

Importing the AAR in your project successfully

I added microsoft-common.aar to app/libs/ in my project (libs may be a new directory that you need to create).

In the dependencies section of my app build.gradle:

    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
    
    // Microsoft MSAL (need to exclude all transitive dependencies or the commons lib will cause a duplicate class error)
    implementation('com.microsoft.identity.client:msal:4.1.0') {
        transitive = false
    }
    
    // Import my modified AAR 
    implementation files('libs/microsoft-common.aar')
    
    // Import required dependencies for common library (excluded by transitive = false above)
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    implementation 'com.microsoft.identity:common4j:6.0.0'
    implementation 'com.yubico.yubikit:android:2.1.0'

Result

Now I can build a release build with both com.microsoft.identity.common.internal.providers.oauth2.AndroidAuthorizationStrategy.java and com.microsoft.identity.common.internal.providers.oauth2.WebViewAuthorizationFragment.java existing in my project. You can grab these classes from https://github.com/AzureAD/microsoft-authentication-library-common-for-android/tree/dev/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2

For those who trust a random on GitHub providing them with a modified AAR, I have attached mine below. For those who don't, just follow the Removing the necessary files from the library steps above.

microsoft-common.aar.zip

RileyGB avatar Dec 01 '22 04:12 RileyGB

@RileyGB Thank you for the provided information. I'll be able to check next week.

I also want to fix WebView not loading after the fragment attachment in the second time. In case if I find something, I'll add the information here.

I think you saved a lot of develops time who faced with it.

VolodaUa avatar Dec 02 '22 07:12 VolodaUa

Regarding the issue with fragment attaching in the second time. This issue with the Webview loading is not present if you don't add the fragment to the back stack. The following code works fine: private fun showFragment(fragment: Fragment) { supportFragmentManager .beginTransaction() .replace(binding.flFragmentContainer.id, fragment) .commit() } The method .addToBackStack(null) is not called.

If you try to add back stack support, it won't work.

VolodaUa avatar Dec 05 '22 13:12 VolodaUa

@VolodaUa Thanks for the feedback on the documentation and sample. We are taking a look and will provide you with updates.

negoe avatar Jan 25 '23 04:01 negoe

Facing the same issue and the work-around of having a local copy of AndroidAuthorizationStrategy is failing in the Release builds.

pulimiharish avatar Feb 21 '23 15:02 pulimiharish

Hello @negoe , is there any update on this issue? I am also having the same problems as stated above. Thanks.

MrThiago avatar Feb 22 '23 09:02 MrThiago

I was able to get this working in release. TLDR; it takes some work.

For my purposes, I wanted to replace both AndroidAuthorizationStrategy.java(this bug) and WebViewAuthorizationFragment.java(I needed access to the webview) with my own implementations.

You may want to get a coffee (or beverage of your choice) before attempting the following:

Removing the necessary files from the library

  • I acquired the AAR for https://github.com/AzureAD/microsoft-authentication-library-common-for-android from my local gradle cache (find an aar in a sub directory of .gradle/caches/modules-2/files-2.1/com.microsoft.identity/common/9.0.0)
  • Since an AAR is just a zip, I renamed its extension to a .zip and unzipped its contents.
  • Within its contents, classes.jar exists. I renamed its extension to a .zip and unzipped its contents.
  • I found and deleted all of the .class files for both AndroidAuthorizationStrategy and WebViewAuthorizationFragment
  • To convert my classes folder to a .jar I ran jar cvf classes.jar classes
  • I took my new classes.jar and put it back in the decompiled aar folder
  • To convert my aar folder to a .aar I ran jar cvf microsoft-common.aar common-9.0.0

Importing the AAR in your project successfully

I added microsoft-common.aar to app/libs/ in my project (libs may be a new directory that you need to create).

In the dependencies section of my app build.gradle:

    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
    
    // Microsoft MSAL (need to exclude all transitive dependencies or the commons lib will cause a duplicate class error)
    implementation('com.microsoft.identity.client:msal:4.1.0') {
        transitive = false
    }
    
    // Import my modified AAR 
    implementation files('libs/microsoft-common.aar')
    
    // Import required dependencies for common library (excluded by transitive = false above)
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    implementation 'com.microsoft.identity:common4j:6.0.0'
    implementation 'com.yubico.yubikit:android:2.1.0'

Result

Now I can build a release build with both com.microsoft.identity.common.internal.providers.oauth2.AndroidAuthorizationStrategy.java and com.microsoft.identity.common.internal.providers.oauth2.WebViewAuthorizationFragment.java existing in my project. You can grab these classes from https://github.com/AzureAD/microsoft-authentication-library-common-for-android/tree/dev/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2

For those who trust a random on GitHub providing them with a modified AAR, I have attached mine below. For those who don't, just follow the Removing the necessary files from the library steps above.

microsoft-common.aar.zip

@RileyGB I tried this approach but getting the below error, any ideas? Thanks com.microsoft.identity.client.exception.MsalServiceException: The resource contains script errors preventing it from being loaded.

pulimiharish avatar Feb 28 '23 17:02 pulimiharish

I was able to get this working in release. TLDR; it takes some work. For my purposes, I wanted to replace both AndroidAuthorizationStrategy.java(this bug) and WebViewAuthorizationFragment.java(I needed access to the webview) with my own implementations. You may want to get a coffee (or beverage of your choice) before attempting the following:

Removing the necessary files from the library

  • I acquired the AAR for https://github.com/AzureAD/microsoft-authentication-library-common-for-android from my local gradle cache (find an aar in a sub directory of .gradle/caches/modules-2/files-2.1/com.microsoft.identity/common/9.0.0)
  • Since an AAR is just a zip, I renamed its extension to a .zip and unzipped its contents.
  • Within its contents, classes.jar exists. I renamed its extension to a .zip and unzipped its contents.
  • I found and deleted all of the .class files for both AndroidAuthorizationStrategy and WebViewAuthorizationFragment
  • To convert my classes folder to a .jar I ran jar cvf classes.jar classes
  • I took my new classes.jar and put it back in the decompiled aar folder
  • To convert my aar folder to a .aar I ran jar cvf microsoft-common.aar common-9.0.0

Importing the AAR in your project successfully

I added microsoft-common.aar to app/libs/ in my project (libs may be a new directory that you need to create). In the dependencies section of my app build.gradle:

    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
    
    // Microsoft MSAL (need to exclude all transitive dependencies or the commons lib will cause a duplicate class error)
    implementation('com.microsoft.identity.client:msal:4.1.0') {
        transitive = false
    }
    
    // Import my modified AAR 
    implementation files('libs/microsoft-common.aar')
    
    // Import required dependencies for common library (excluded by transitive = false above)
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    implementation 'com.microsoft.identity:common4j:6.0.0'
    implementation 'com.yubico.yubikit:android:2.1.0'

Result

Now I can build a release build with both com.microsoft.identity.common.internal.providers.oauth2.AndroidAuthorizationStrategy.java and com.microsoft.identity.common.internal.providers.oauth2.WebViewAuthorizationFragment.java existing in my project. You can grab these classes from https://github.com/AzureAD/microsoft-authentication-library-common-for-android/tree/dev/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2 For those who trust a random on GitHub providing them with a modified AAR, I have attached mine below. For those who don't, just follow the Removing the necessary files from the library steps above. microsoft-common.aar.zip

@RileyGB I tried this approach but getting the below error, any ideas? Thanks com.microsoft.identity.client.exception.MsalServiceException: The resource contains script errors preventing it from being loaded.

I also encountered the same issue with 4.1.0. It works fine with the previous version.

VolodaUa avatar Feb 28 '23 17:02 VolodaUa

@VolodaUa Thank you for the info, can you please let me know which version(s) worked for you?

    // Microsoft MSAL (need to exclude all transitive dependencies or the commons lib will cause a duplicate class error)
    implementation("com.microsoft.identity.client:msal:4.0.5") {
        transitive = false
    }

    // Import required dependencies for common library (excluded by transitive = false above)
    implementation("androidx.constraintlayout:constraintlayout:2.1.0-beta01")
    implementation "com.microsoft.identity:common4j:6.0.0"
    implementation "com.yubico.yubikit:android:2.1.0"

but still getting the same error

Authorization Status: FAIL
Removing alias: return_authorization_request_result
Removing alias: cancel_authorization_request
Authentication failed: com.microsoft.identity.client.exception.MsalServiceException: The resource contains script errors preventing it from being loaded.

pulimiharish avatar Feb 28 '23 18:02 pulimiharish

@pulimiharish

Please try this code:

` // Microsoft MSAL (need to exclude all transitive dependencies or the commons lib will cause a duplicate class error) //noinspection GradleDependency implementation('com.microsoft.identity.client:msal:4.0.5') { transitive = false }

// Import the modified AAR fith the fix
implementation files('libs/microsoft-idenity-common-8.0.3.aar')

// Import required dependencies for common library (excluded by transitive = false above)
//noinspection GradleDependency
implementation("androidx.constraintlayout:constraintlayout:1.1.3")
implementation 'com.microsoft.identity:common4j:6.0.0'
implementation 'com.yubico.yubikit:android:2.1.0'`

VolodaUa avatar Mar 08 '23 13:03 VolodaUa

@negoe Could you please tell me whether the issue is fixed? I don't see any pull request with the fix, but the ticket was closed.

VolodaUa avatar Jun 08 '23 10:06 VolodaUa

@negoe Please reopen the ticket or tell me if I need to create it again.

The fix is not present in the latest version 4.10.0.

I can't capture why a simple fix was skipped and people still need to do a workaround to make it work ((((

AuthorizationFragment#finish | [2023-12-29 13:55:09 - thread_id: 2, correlation_id: UNSET - Android 33] Logged as error to capture 'cause'; Exception occurred when removing ourselves from provided FragmentManager java.lang.IllegalStateException: FragmentManager is already executing transactions at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1717) at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1747) at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:317) at com.microsoft.identity.common.internal.providers.oauth2.AuthorizationFragment.finish(AuthorizationFragment.java:136) at com.microsoft.identity.common.internal.providers.oauth2.AuthorizationFragment.onCreate(AuthorizationFragment.java:94) at com.microsoft.identity.common.internal.providers.oauth2.WebViewAuthorizationFragment.onCreate(WebViewAuthorizationFragment.java:101) at androidx.fragment.app.Fragment.performCreate(Fragment.java:3094) at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:504) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:268) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1943) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1839) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1782) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:565) at android.os.Handler.handleCallback(Handler.java:942) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8762) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067) 2023-12-29 15:55:09.178 5029-5214 Authorizat...ent#finish com.schindler.mobile.myport E [2023-12-29 13:55:09 - thread_id: 2, correlation_id: UNSET - Android 33] Logged as error to capture 'cause'; Exception occurred when removing ourselves from provided FragmentManager

Thanks for answer!

VolodaUa avatar Dec 29 '23 14:12 VolodaUa

I have similar problem here.

And the work-around did not work.

Environment: MSAL: implementation('com.microsoft.identity.client:msal:4.10.0') Android: 14, the problem also occour in 13 and 12 version.

Configuration file:

{
    "client_id" : "XXXXXXX",
    "authorization_user_agent" : "DEFAULT",
    "redirect_uri" : "msauth://com.xxxxxx/xxxxxxxxx",
    "broker_redirect_uri_registered": true,
    "loggin":  "VERBOSE",
    "shared_device_mode_supported": true,
    "authorities" : [
        {
            "type": "AAD",
            "audience": {
                "type": "AzureADMyOrg",
                "tenant_id": "xxxxxxxx"
            }
        }
    ]
}

aquire token:

microsoftClient?.acquireToken(
                AcquireTokenParameters.Builder()
                    .startAuthorizationFromActivity(it)
                    .withPrompt(Prompt.LOGIN)
                    .withScopes(SCOPES)
                    .withCallback(object : AuthenticationCallback {
                        override fun onSuccess(authenticationResult: IAuthenticationResult?) {
                            msalCallback?.onLogin(authenticationResult)
                        }

                        override fun onError(exception: MsalException) {
                            msalCallback?.onError(exception)
                        }

                        override fun onCancel() {
                            msalCallback?.onCancel()
                        }
                    })
                    .build()
            )

Scope: profile, if we change to User.Read, the user need to use the MFA. This is the reason of we use the profile scope. Broker: Intune Company portal

The AndroidAuthorizationStrategy class is now in the project https://github.com/AzureAD/microsoft-authentication-library-common-for-android/tree/release/16.2.0

I did not receive any error message, and I am trying to get it.

If you can get me any tip I will appreciate ;)

fvaladares avatar Jan 05 '24 21:01 fvaladares

Hi @fvaladares ,

As I see, your problem is different. This problem relates to the issue when the "withFragment()" method is used using AcquireTokenParameters.Bulder.

I suggest you add logging. Maybe you will find something there. https://learn.microsoft.com/en-us/entra/identity-platform/msal-logging-android

VolodaUa avatar Jan 08 '24 10:01 VolodaUa

Hi @VolodaUa,

Thanks for ask my question. I will take a look in your suggestion and make some tests.

fvaladares avatar Jan 08 '24 13:01 fvaladares