I'm trying to figure out what would be the best way to implement a Retrofit client which supports AccountManager.getAuthToken() for OAuth2 flow. I'm following the U2020
Ideally I would like to have a simple injector along these lines
public class ExampleFragment extends InjectionFragment { @Inject ApiDatabase database; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); subscribe(database.getSomeData(), ...); } }
I'm considering a RequestInterceptor similar to the example
public final class ApiHeaders implements RequestInterceptor { ApiKeyProvider apiKeyProvider; @Inject public ApiHeaders(ApiKeyProvider apiKeyProvider) { this.apiKeyProvider = apiKeyProvider; } @Override public void intercept(RequestFacade request) { // How to handle exceptions from getAuthToken? request.addHeader("Authorization", "Bearer " + apiKeyProvider.getAuthKey()); } }
and
public class ApiKeyProvider { AccountManager accountManager; Activity activity; public ApiKeyProvider(Activity activity, AccountManager accountManager) { this.activity = activity; this.accountManager = accountManager; } public String getAuthKey() throws AccountsException, IOException { AccountManagerFuture accountManagerFuture = accountManager.getAuthTokenByFeatures(ACCOUNT_TYPE, AUTHTOKEN_TYPE, new String[0], activity, null, null, null, null); return accountManagerFuture.getResult().getString(KEY_AUTHTOKEN); } }
I'm not sure how to inject the ApiKeyProvider into the ApiHeaders class as it depends on an "ActivityModule" (lower down the dagger DAG graph). Also not sure how to handle exceptions.
Can anyone provide a full working example?
This ended up being a little lengthy. This GIST hopefully encompasses all the relevant files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With