Home > Net >  Obtaining accessToken for google sign-in (Android)
Obtaining accessToken for google sign-in (Android)

Time:10-06

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)
    }

}

CodePudding user response:

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)

CodePudding user response:

Do you want to use google login and then you first check your sha1 key for more healp please watch this video just click this link : https://youtu.be/bBJF1M5h_UU

  • Related