简体   繁体   English

获取谷歌登录的accessToken(安卓)

[英]Obtaining accessToken for google sign-in (Android)

I'm using Google sign-in in my application我在我的应用程序中使用 Google 登录

the problem is that I want to obtain accessToken to send it to the back end server, but the GoogleSignInAccount dosen't have it问题是我想获取accessToken以将其发送到后端服务器,但GoogleSignInAccount没有它

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 .我怀疑您可能必须将AuthCredentialOAuthCredential才能获取accessToken Try the below.试试下面的。 Note, I did not run this code to verify.注意,我没有运行这段代码来验证。 Some additional information here: Firebase Docs这里有一些附加信息: Firebase 文档

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.似乎 Android SDK 没有提供获取访问代码的简单方法。

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:查看此链接以获取另一个选项: GoogleAuthUtil请注意链接中提到的一些信息,例如运行此异步等。您可能可以获得访问令牌,因此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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