简体   繁体   中英

Obtaining accessToken for google sign-in (Android)

I'm using Google sign-in in my application

the problem is that I want to obtain accessToken to send it to the back end server, but the GoogleSignInAccount dosen't have it

private fun handleGoogleSignInResult(task: Task<GoogleSignInAccount>) {

    task.addOnSuccessListener { googleSignInAccount ->

        // TODO: Obtaining accessToken

    }

    task.addOnFailureListener { e ->
        Timber.e(e)
        showToast(R.string.something_went_wrong_try_again_later)
    }

}

I suspect you might have to cast the AuthCredential to OAuthCredential to get the accessToken . Try the below. Note, I did not run this code to verify. Some additional information here: Firebase Docs

private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        val auth = Firebase.auth
        auth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    val user = auth.currentUser
                    val oAuthCredential = credential as OAuthCredential
                    val token = oAuthCredential.accessToken
                } else {
                    // If sign in fails, display a message to the user.
                }
            }
    }

UPDATE The above fails as casting fails.

Seems like the Android SDK does not provide an easy way to get the access code.

Have a look at this link for another option: GoogleAuthUtil Beware of some of the info mentioned in the link like running this async etc. You might be able to get the access token so:

val scope = "oauth2:" + Scopes.EMAIL + " " + Scopes.PROFILE;
                    val account = GoogleSignIn.getLastSignedInAccount(this)
                    val token = GoogleAuthUtil.getToken(this, account?.account, scope)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM