Superdry Memorandom :-p

旧「superdry memorandum :-D」です

tab APIを使ったAndroidサンプルアプリ(2)

前回のエントリの続きです。今回はtabAndroidサンプルアプリケーションの詳細について説明します。

OAuthの認可コードの取得

tabの認証系・更新系APIを使うためにはアクセストークンが必要ですが、その前にまず、アクセストークンを取得するための認可コードの発行が必要です。これはGetAccessTokenActivity.javaのgetAuthorizationCode内で実装しています。

private final OnClickListener getAuthorizationCode = new View.OnClickListener() {

  @Override
  public void onClick(View v) {

    // 認可コードの取得
    OAuthClientRequest request = null;
    try {
      request = OAuthClientRequest
          .authorizationLocation(
              CommonConst.AUTHORIZATION_LOCATION)
          .setResponseType("code")
          .setClientId(CommonConst.CLIENT_ID)
          .setRedirectURI(CommonConst.REDIRECT_URI)
          .buildQueryMessage();
    } catch (OAuthSystemException e) {
      e.printStackTrace();
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request
        .getLocationUri()));
    startActivity(intent);
  }
};

認可コードの取得のUriを組み立て(L9〜L15)、Uriをブラウザに対し暗黙的インテントを投げています(L20〜22)。ブラウザに表示されるtabの認可画面で許可すると、ブラウザはコールバックURLへリダイレクトします。GetAccessTokenActivityは、コールバックURLに対応するサービスとしても登録されています。コールバックURLを受け取ったGetAccessTokenActivityは、getAccessToken内で認可コードを取得しています。

private void getAccessToken(Intent intent) {
  Uri uri = intent.getData();

  if (uri != null && uri.toString().startsWith(CommonConst.REDIRECT_URI)) {

    // エラーチェック
    String error = uri.getQueryParameter("error");
    if (error != null) {
      // 中略
    } else {

      // 認可コードの取得
      String code = uri.getQueryParameter("code");
      GetAccessTokenTask task = new GetAccessTokenTask(this, code);
      task.execute();
    }
  }
}

ここで、認可コードを取得し(L13)、アクセストークンの取得処理(L14〜L15)が実行されます。

アクセストークンの取得

アクセストークンの取得は、GetAccessTokenTask.javaのdoInBackground内で実装しています。

@Override
  protected Void doInBackground(Void... arg0) {
    OAuthClientRequest request = null;
    OAuthJSONAccessTokenResponse response = null;

    try {
      request = OAuthClientRequest
          .tokenLocation(CommonConst.TOKEN_LOCATION)
          .setGrantType(GrantType.AUTHORIZATION_CODE)
          .setClientId(CommonConst.CLIENT_ID)
          .setClientSecret(CommonConst.CLIENT_SECRET)
          .setRedirectURI(CommonConst.REDIRECT_URI)
          .setCode(mCode).buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

      response = oAuthClient.accessToken(request);
    } catch (OAuthSystemException e) {
      e.printStackTrace();
    } catch (OAuthProblemException e) {
      e.printStackTrace();
    }

    if (response != null) {
      SharedPreferences pref = mContext.getSharedPreferences(CommonConst.PREF_NAME,
          Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = pref.edit();
      editor.putString(CommonConst.PREF_ACCESS_TOKEN, response.getAccessToken());
      editor.putString(CommonConst.PREF_REFRESH_TOKEN, response.getRefreshToken());
      editor.putString(CommonConst.PREF_EXPIRES_IN, response.getExpiresIn());
      editor.putString(CommonConst.PREF_TOKEN_TYPE, response.getParam("token_type"));
      editor.apply();
    }

    return null;
  }

OAuthClientRequestを組み立て(L7〜L13)、アクセストークンを再取得(L17)しています。

なお、このサンプルアプリケーションでは取得したアクセストークンはSharedPreferencesに保存しています(L25〜L32)。セキュリティが気になる人はここでトークンを暗号化して保存するとなおよいでしょう。SharedPreferencesに保存されたアクセストークンをつかって、tabの認証系・更新系APIにアクセスすることができます。

リフレッシュトークンによるアクセストークンの再取得

アクセストークンには期限があるため、期限切れの場合はAPIアクセスのタイミングで401(Unauthorized)を返します。その場合は、以前アクセストークンを取得したときについてきたリフレッシュトークンを使い、アクセストークンを再取得する必要があります。

サンプルアプリケーションでは、RefreshTokenTask.javaのdoInBackground内で実装しています。

@Override
protected Void doInBackground(Void... arg0) {
  OAuthClientRequest request = null;
  OAuthJSONAccessTokenResponse response = null;

  try {
    request = OAuthClientRequest
        .tokenLocation(CommonConst.TOKEN_LOCATION)
        .setGrantType(GrantType.REFRESH_TOKEN)
        .setClientId(CommonConst.CLIENT_ID)
        .setClientSecret(CommonConst.CLIENT_SECRET)
        .setRefreshToken(mToken).buildBodyMessage();

    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

    response = oAuthClient.accessToken(request);
  } catch (OAuthSystemException e) {
    e.printStackTrace();
  } catch (OAuthProblemException e) {
    e.printStackTrace();
  }

  if (response != null) {
    SharedPreferences pref = mContext.getSharedPreferences(CommonConst.PREF_NAME,
        Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(CommonConst.PREF_ACCESS_TOKEN, response.getAccessToken());
    editor.putString(CommonConst.PREF_REFRESH_TOKEN, response.getRefreshToken());
    editor.putString(CommonConst.PREF_EXPIRES_IN, response.getExpiresIn());
    editor.putString(CommonConst.PREF_TOKEN_TYPE, response.getParam("token_type"));
    editor.apply();
  }

  return null;
}

アクセストークンと同じように、OAuthClientRequestを組み立て(L7〜L12)、アクセストークンを再取得(L16)しています。違うのはOAuthClientRequestを組み立て方のみです。取得した情報は、これも同様に、SharedPreferencesに上書き保存しています(L24〜L31)。

まとめ

以上で、tab APIを使ったAndroidサンプルアプリケーションの説明は終わります。現時点で、tab APIを使っているアプリはこちらでご紹介しています。今後もいろいろなAPIを充実させていく予定ですので、ぜひ使ってみてください!