Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing OAuth2 with AccountManager, Retrofit and Dagger

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?

like image 343
Alon Burg Avatar asked Jun 09 '14 18:06

Alon Burg


1 Answers

This ended up being a little lengthy. This GIST hopefully encompasses all the relevant files

like image 107
Alon Burg Avatar answered Nov 08 '22 20:11

Alon Burg