我终于找到了解决方案。使用此处找到的教程。
您必须在 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());