android – 将授权的Google Cloud Endpoints与Google登录一起使用
作者:互联网
我有一个使用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.
那么,有可能这样做吗?该怎么做?
解决方法:
我终于找到了解决方案.使用教程找到here.
您必须在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());
标签:android,google-play-services,google-cloud-endpoints,googlesigninaccount 来源: https://codeday.me/bug/20190516/1116326.html