当前位置:  开发笔记 > 编程语言 > 正文

将授权的Google Cloud Endpoints与Google登录一起使用

如何解决《将授权的GoogleCloudEndpoints与Google登录一起使用》经验,为你挑选了1个好方法。

我有一个使用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.

那么,有可能这样做吗?该怎么做?



1> 9and3r..:

我终于找到了解决方案.使用此处的教程.

您必须在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());

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有