3

Android で Google Play サービスを使用して、Google API と Google クラウド エンドポイントにアクセスしています。また、Google Play Services からのトークンを使用して、appengine User API にアクセスすることもできます。これは可能ですか?このリンクに OAuth のサンプル コードがいくつかありますが、少しあいまいです。ヘッダーに oauth トークンを渡して、以下のコードでユーザーを取得できますか??

    User user = null;
    try {
        OAuthService oauth = OAuthServiceFactory.getOAuthService();
        user = oauth.getCurrentUser();

    } catch (OAuthRequestException e) {
        // The consumer made an invalid OAuth request, used an access token that was
        // revoked, or did not provide OAuth information.
        // ...
    }
4

1 に答える 1

6

可能ですが、このアプローチは、次のようなシナリオほど安全ではありません。

  • Google API のサービス固有のスコープを使用する
  • Endpoints API に直接アクセスする

Google Play Services を使用して、使用したいスコープのトークンを取得できます。UsersApp Engine で API を使用することに関心があるため、次のuserinfo.emailスコープが必要になります。

String mScope = "https://www.googleapis.com/auth/userinfo.email";
try {
    token = GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch {
    ...
}

これを Authorization ヘッダー経由で App Engine に送信します。

Authorization: Bearer your_token

次に、OAuthAPI を使用してUserオブジェクトを取得できます。

String mScope = "https://www.googleapis.com/auth/userinfo.email";
User user = null;
try {
  OAuthService oauth = OAuthServiceFactory.getOAuthService();
  user = oauth.getCurrentUser(mScope);
} catch (OAuthRequestException e) {
  // The consumer made an invalid OAuth request, used an access token that was
  // revoked, or did not provide OAuth information.
  // ...
}

しかし、一般的にはこれをしたくありません! この方法でアプリケーションを保護すると、別のユーザーが、userinfo.emailスコープへのアクセス許可を求めるアプリケーションを作成できます。付与されたら、トークンを取得しアプリケーションに渡すだけで、ユーザーと同じように表示されます。エンドポイントやその他の Google API には、この種の動作を防ぐための追加のロジックが用意されているため、これらのアプローチのいずれかを使用することをお勧めします。

于 2012-11-21T21:08:23.127 に答える