我有一个使用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,但是从Google登录我获得GoogleSignInAccount。
那么,有可能这样做吗?该怎么做?
答案 0 :(得分:6)
我终于找到了解决方案。使用教程找到了here。
您必须在GoogleSignInOptions中添加客户端ID:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.build();
credential.setAccessToken(GoogleSignInAccount.getIdToken());
按照教程,您将最终获得GoogleSignInAccount。在GoogleCredential对象中设置来自GoogleSignInAccount的令牌:
credential = GoogleAccountCredential.usingAudience(this,
"server:client_id:1-web-app.apps.googleusercontent.com");
此凭据已准备好对Google Cloud Enpoints进行经过身份验证的调用。
请注意,您必须删除" server:client_id:"部分来自CLIENT_ID。所以如果你使用它:
CLIENT_ID = "1-web-app.apps.googleusercontent.com"
您的CLIENT_ID将是:
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());
另请注意,令牌在有限的时间内有效(Aprox.1小时测试)
要避免1小时令牌限制,请在每次拨打终端之前使用GoogleSignInApi.silentSignIn()获取新令牌。例如,如果您不在UI线程中:
{{1}}