使用AccountManager,Retrofit和Dagger实现OAuth2

时间:2014-06-09 18:50:26

标签: android oauth-2.0 accountmanager retrofit dagger

我正在试图找出实现支持OAuth2流的AccountManager.getAuthToken()的Retrofit客户端的最佳方法。 我正在关注U2020

理想情况下,我希望沿着这些线有一个简单的注射器

public class ExampleFragment extends InjectionFragment {
  @Inject ApiDatabase database;

  @Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    subscribe(database.getSomeData(), ...);
  }
}

我正在考虑类似于the example

的RequestInterceptor
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());
  }
}

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);
  }
}

我不确定如何将ApiKeyProvider注入ApiHeaders类,因为它依赖于“ActivityModule”(在匕首DAG图下方)。 也不知道如何处理异常。

任何人都可以提供完整的工作示例吗?

1 个答案:

答案 0 :(得分:5)

这最终有点冗长。 This GIST希望包含所有相关文件