I have been using the B2CModeFragment class from the Use MSAL in an Android app to sign-in users and call Microsoft Graph which has been very helpful in getting B2C running in my app and I can call a web api which requires authentication. However, I am struggling with how to implement the solution in other areas. I need to call web apis throughout my app from multiple fragments. I currently have all the B2C functions working in a settings fragment where I can select the user. At that point I have the B2C user and have authenticated silently. Using:
user.acquireTokenSilentAsync(b2cApp, B2CConfiguration.getPolicy(), B2CConfiguration.getScopes(), new SilentAuthenticationCallback()
The b2cApp is a private variable in the settings fragment:
private IMultipleAccountPublicClientApplication b2cApp;
Should I call the the acquireTokenSilentAsync before every api call? The tokens only last for an hour so I can't assume I have a token and I read this article showing:
headers.put("Authorization", "Bearer " + authResult.getAccessToken());
I was previously storing the token in SharedPreferences and using it but it only lasts an hour and I have to refresh the token from another fragment when it fails. I could keep the b2cuser object around but would still need the b2cApp to make a silent call.
What was the intent of the b2capp and b2cuser. Do I keep them in the MainActivity, do I extend the Application and keep them there, do I encapsulate them in an object and instantiate it on authentication failure when calling an api to get another one?
I also want to note that the app can work offline completely so successful api calls need to happen at some point but are not required for the app to function.