5

我有一个使用 Google Cloud Endpoints 的应用程序。有些方法需要授权,所以我按照教程进行操作。这需要 GET_ACCOUNTS 权限。

我正在更新应用程序以使用运行时权限。我不喜欢请求读取联系人的权限,但 GET_ACCOUNTS 在同一个组中。因此,我希望在没有 GET_ACCOUNTS 许可的情况下使用授权。

我认为谷歌登录可以工作,但我无法找到使用谷歌登录结果的方法。

这是用于创建对象以调用端点的代码:

Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,credential);

凭据对象必须是HttpRequestInitializer但从 Google Sign In 我得到GoogleSignInAccount

那么,有可能做到这一点吗?这应该怎么做?

4

1 回答 1

6

我终于找到了解决方案。使用此处找到的教程。

您必须在 GoogleSignInOptions 中添加客户端 ID:

 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(CLIENT_ID)
            .requestEmail()
            .build();

按照教程,您最终将获得一个 GoogleSignInAccount。在 GoogleCredential 对象中设置来自 GoogleSignInAccount 的令牌:

GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
            .setJsonFactory(JacksonFactory.getDefaultInstance())
            .build();
credential.setAccessToken(GoogleSignInAccount.getIdToken());

此凭据已准备好对 Google Cloud Enpoints 进行经过身份验证的调用。

请注意,您必须从 CLIENT_ID 中删除“server:client_id:”部分。所以如果你使用这个:

credential = GoogleAccountCredential.usingAudience(this,
    "server:client_id:1-web-app.apps.googleusercontent.com");

您的 CLIENT_ID 将是:

CLIENT_ID = "1-web-app.apps.googleusercontent.com"

另请注意,令牌在有限的时间内有效(在我的测试中大约 1 小时)

为避免 1 小时令牌限制,请在每次调用端点之前使用GoogleSignInApi.silentSignIn()获取新令牌。例如,如果您不在 UI 线程中:

GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail()
                .requestIdToken(CLIENT_ID)
                .build();
GoogleSignInClient client = GoogleSignIn.getClient(context, options);
GoogleSignInAccount user = Tasks.await(getGoogleSignInClient(context).silentSignIn());

// Use the new user token as before 
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
        .setJsonFactory(JacksonFactory.getDefaultInstance())
        .build();
credential.setAccessToken(user.getIdToken());
于 2016-02-22T00:49:50.237 回答