Silent sign in to retrieve token with GoogleApiClient

后端 未结 3 2112
难免孤独
难免孤独 2020-12-05 14:08

I am using \"Google Sign-In\" in my app. Hence I use the class GoogleApiClient to get the user email and the ID token that I need for my backend.

When the user signs

相关标签:
3条回答
  • 2020-12-05 14:38

    I found the problem. I was under the impression that the function

    OptionalPendingResult<GoogleSignInResult> pendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
    

    was going to connect the mGoogleApiClient for me (since it returns a pending result). However, that was not the case and in order to solve the above I just needed to add the call

    ConnectionResult result = mGoogleApiClient.blockingConnect();
    

    in the beginning of the silentLogin method. (and then of course disconnect later on, and also make sure the call is made in a thread different from main thread)

    tada'

    0 讨论(0)
  • 2020-12-05 14:46

    Yes, answer above is correct. In general, any GoogleApiClient needs to be connected before it can return you any data. enableAutoManage helps you to call connect() / disconnect() automatically during onStart() / onStop(). If you don't use autoManage, you will need to connect() manually.

    And even better, you should disconnect in a finally block.

    Assuming you are not on the UI thread.

    try {
        ConnectionResult result = mGoogleApiClient.blockingConnect();
        if (result.isSuccess()) {
            GoogleSignInResult googleSignInResult =
                Auth.GoogleSignInApi.silentSignIn(googleApiClient).await();
        ...
        }
    } finally {
        mGoogleApiClient.disconnect();
    }
    

    And also, to clean up your code a little bit: 1. gso built from below configuration is identical to your pasted code above:

    GoogleSignInOptions gso =
       new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(SERVER_CLIENT_ID)
            .requestEmail()
            .build();
    
    1. Based on your current logic, addOnConnectionFailedListener / addConnectionCallbacks doesn't help other than adb log. Maybe just remove them completely?
    0 讨论(0)
  • 2020-12-05 14:56

    To add to the two answers above by Isabella and Ola, if you're using the new sign in lib with Firebase:

    FirebaseAuth.getInstance().currentUser?.let{ 
        //create sign-in options the usual way
        val googleSignInClient = GoogleSignIn.getClient(context, gso)
        googleSignInClient.silentSignIn().addOnCompleteListener {
            val account: GoogleSignInAccount? = it.result
            //get user info from account object
        }
    }
    

    Also, this can be called from the UI thread. FirebaseAuth.getInstance().currentUser will always return the user object if you have signed in once before.

    0 讨论(0)
提交回复
热议问题