我有一个使用 Google Cloud Endpoints 的应用。有些方法需要授权所以我跟着this教程。这需要 GET_ACCOUNTS 权限。
我正在更新应用程序以使用运行时权限。我不喜欢请求读取联系人的权限,但 GET_ACCOUNTS 在同一组中。因此,我希望在没有 GET_ACCOUNTS 许可的情况下使用授权。
我认为 Google Sign In可以工作,但我找不到使用 Google 登录结果的方法。
这是用于创建对象以调用端点的代码:
Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,credential);
凭证对象必须是 HttpRequestInitializer但是从谷歌登录我得到一个GoogleSignInAccount .
那么,这样做有可能吗?应该怎么做?
最佳答案
我终于找到了解决方案。使用教程发现here .
您必须在 GoogleSignInOptions 中添加客户端 ID:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(CLIENT_ID)
.requestEmail()
.build();
按照教程,您最终会获得一个 GoogleSignInAccount。在 GoogleCredential 对象中设置来自 GoogleSignInAccount 的 token :
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"
另请注意, token 在有限的时间内有效(在我的测试中约为 1 小时)
要避免 1 小时 token 限制,请使用 GoogleSignInApi.silentSignIn()在每次调用端点之前获取新 token 。例如,如果您不在 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());
关于android - 通过 Google 登录使用授权的 Google Cloud Endpoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34476261/