我有一个使用Google Cloud Endpoints的应用.有些方法需要授权,所以我遵循了本教程.这需要GET_ACCOUNTS权限.
我正在更新应用程序以使用运行时权限.我不想请求读取联系人的权限,但GET_ACCOUNTS属于同一组.因此,我希望在没有GET_ACCOUNTS许可的情况下使用授权.
我认为Google登录可行,但我无法找到使用Google登录结果的方法.
这是用于创建对象以调用端点的代码:
Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,credential);
凭证对象必须是HttpRequestInitializer,但是从Google登录我获得GoogleSignInAccount.
那么,有可能这样做吗?该怎么做?
我终于找到了解决方案.使用此处的教程.
您必须在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"
另请注意,令牌在有限的时间内有效(Aprox.在我的测试中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());