Android auth_token 验证和使用服务器端

标签 android google-api oauth-2.0

如何验证返回的 auth_token

token = bundle.getString(AccountManager.KEY_AUTHTOKEN);

?

在 Android 上获得新用户后,我需要将它们插入我的数据库服务器端,但我需要在执行之前以某种方式验证该 token 。

我正在尝试像这样使用 token :

url = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=%s' % access_token

但 Google 返回“未经授权的访问”。

如何访问

https://www.googleapis.com/oauth2/v1/userinfo

使用 Android AccountManager 提供的“auth_token”?

最佳答案

您可能只是缺少 authTokenType 前面的 oauth2: 前缀。

此代码有效:

// Note the `oauth2:` prefix
private static final String AUTH_TOKEN_TYPE_USERINFO_PROFILE =
    "oauth2:https://www.googleapis.com/auth/userinfo.profile";

// TODO: allow the use to choose which account to use
Account acct = accountManager.getAccountsByType("com.google")[0];

accountManager.getAuthToken(acct, AUTH_TOKEN_TYPE_USERINFO_PROFILE,
    null, this, new AccountManagerCallback<Bundle>() {
      @Override
      public void run(AccountManagerFuture<Bundle> future) {
        try {
          String accessToken = future.getResult().getString(
              AccountManager.KEY_AUTHTOKEN);
          Log.i(TAG, "Got OAuth2 access token: " + accessToken);
          /*
             Your code here. Use one of two options. In each case replace ... with
             the above OAuth2 access token:

             1) GET https://www.googleapis.com/oauth2/v1/userinfo?access_token=...

             2) GET https://www.googleapis.com/oauth2/v1/userinfo with this header:
                Authorization: Bearer ...
          */
        } catch (OperationCanceledException e) {
          // TODO handle this case
          Log.w(TAG, "The user has did not allow access");
        } catch (Exception e) {
          // TODO handle this exception
          Log.w(TAG, "Unexpected exception", e);
        }
      }
    }, null);

关于Android auth_token 验证和使用服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8583074/

相关文章:

android - ListView 不在 App Widget 中显示数据

java - android - 滑动时动画

google-api - 使用服务帐户使用 Google Drive API 创建文件不会在授权用户帐户的 GD 上呈现文件

azure - 此请求的授权已被拒绝 - Azure Active Directory - 有哪些日志可用?

c# - JWT 和 Web API(JwtAuthForWebAPI?)——寻找示例

Android 为什么以所需格式解析日期时间需要大约 50-60 毫秒?

android - 无效的 JNI 引用(从 C++ 调用 Java 方法)

google-api - Google Analytics API 请求返回验证码?

database - 我是否需要覆盖存储在数据库中的 Google Analytics 数据

oauth-2.0 - IdentityServer 3返回invalid_client