google-api - 我应该将 ID token 永久存储在 Google 登录中吗?

标签 google-api google-signin

我在我的应用程序中使用 Google 登录,一旦用户登录并检索到 ID token ,我就会将 ID token 发送到我的反手服务器。现在,我将 ID token 添加到每个 HTTP 请求的 header 中,并对其进行验证,获取用户 ID 并将数据响应回我的应用程序。我想知道是否可以永久存储 ID token 并将其用于所有 future 的请求。 ID token 会更改或过期一段时间吗?如果是这样,如何获得新的 ID token ?除了要求用户再次登录之外,我找不到任何方法。还是我应该只验证一次 ID token 并在以后的请求中直接使用 ID?

最佳答案

不要存储 ID token 。 Google ID token 的有效期为一小时,将过期,您只需使用 silentSignIn在您的应用程序中获得一个新的,而无需任何用户交互。如果您现有的 token 尚未过期,您将获得(缓存的)版本(返回的 OptionalPendingResult 将有 isDone() == true);如果它已经过期,你会得到一个刷新的(但它会花费更长的时间,因此 OptionalPendingResult isDone() 将是 false )。

这里是 sample code (UI 线程,请参阅下面关于工作线程的注释):

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.server_client_id))

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

...

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
    if (opr.isDone()) {
        // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
        // and the GoogleSignInResult will be available instantly.
        Log.d(TAG, "Got cached sign-in");
        GoogleSignInResult result = opr.get();
        handleSignInResult(result);  // result.getSignInAccount().getIdToken(), etc.
    } else {
        // If the user has not previously signed in on this device or the sign-in has expired,
        // this asynchronous branch will attempt to sign in the user silently.  Cross-device
        // single sign-on will occur in this branch.
        opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(GoogleSignInResult googleSignInResult) {
                handleSignInResult(googleSignInResult);  // result.getSignInAccount().getIdToken(), etc.
            }
        });
    }

请记住您是否调用 silentSignIn在 UI 线程或工作线程上。如果您在工作线程上调用它,请查看这篇带有 blockingConnect() 的帖子+ await()这大大简化了代码:
Silent sign in to retrieve token with GoogleApiClient

关于google-api - 我应该将 ID token 永久存储在 Google 登录中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644069/

相关文章:

php - 访问 Google_Service_Exception 中的属性时出现问题

google-api - 如何授权服务帐户访问 Google Admin API

android - android中的谷歌登录授权错误

firebase - 谷歌登录在模拟器上工作但不在 Android 设备上工作 flutter

php - 使用 HelloAnalyticsApi 时调用 Google Analytics 中未定义的方法 Google_Client

node.js - 如何获取Google Ads API以获取帐户列表

php - 在谷歌日历上同步约会时收到警告?

java - 有没有办法限制 Android 中的 Google 登录到某个电子邮件域?

android - 从 Play 商店安装应用程序后尝试使用谷歌登录时出现 'Error authenticating with Google: unknown' 异常。查看具体信息

android - 错误 : execution failed for task '.app:buildInfoDebugLoader'