我的IDToken过期后,如何从Google Api Client获取另一个IDToken?

时间:2019-07-01 18:00:51

标签: android google-api-client

在我的Android应用中,我通过Google Api Client使用Google登录。 我获得了IDToken,并将其与服务器的WebService一起使用。我的问题是该IDToken已过期,我无法再获得另一个。当我执行新的googleSignInClient.silentSignIn()时,IDToken相同。

如何获取新的IDToken?

我执行以下步骤:

1.-在LoginActivity中:

GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.server_client_id))
            .requestEmail()
            .build();
    googleSignInClient = GoogleSignIn.getClient(this, gso);

    googleSignInClient.silentSignIn()
            .addOnCompleteListener(this, new 
OnCompleteListener<GoogleSignInAccount>() {
                @Override
                public void onComplete(@NonNull Task<GoogleSignInAccount> 
task) {
                    handleSignInResult(task);
                }
            });

    GoogleSignInAccount alreadyloggedAccount = 
GoogleSignIn.getLastSignedInAccount(this);
    if (alreadyloggedAccount != null) {
        Toast.makeText(this, "Already Logged In", 
Toast.LENGTH_SHORT).show();
        account = alreadyloggedAccount;
        idToken = account.getIdToken();
        SharedPreferences prefs = 
 getSharedPreferences("Preferences",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("IDToken",idToken);
        editor.commit();
        onLoggedIn(alreadyloggedAccount);

    } else {
        Log.d(TAG, "Not logged in");
        updateUI(false);
    }   

2.-当我调用WebService并获得IDToken过期以获取另一个IDToken时,我这样做:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.server_client_id))
                    .requestEmail()
                    .build();
            GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(PeliculaDetailActivity.this, gso);

            googleSignInClient.silentSignIn()
                    .addOnCompleteListener(PeliculaDetailActivity.this, new OnCompleteListener<GoogleSignInAccount>() {
                        @Override
                        public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                            try {
                                GoogleSignInAccount account = task.getResult(ApiException.class);
                                String idToken2 = account.getIdToken();
                                if (idtoken.equals(idToken2)){
                                    idtoken=idToken2;
                                }
                                //CALL WebService with the new IDToken
                            } catch (ApiException e) {
                                Log.w("", "signInResult:failed code=" + e.getStatusCode());
                            }
                        }
                    });

谢谢。

0 个答案:

没有答案