In Android Studio, getting the following Kotlin error in Logcat:
[RequestTokenManager] getToken() -> BAD_AUTHENTICATION. App: com.example.packagename, Service: oauth2:openidamnk: Long live credential not available.
When I click on the Login with Google button in my app, I get this error from the catch statement for the exception: No credentials available.
I've been looking at it for hours and unable to figure it out. This is not a duplicate because other answers are more than 3 years old with no solution that worked for me.
Here is my code:
fun sighInWithGoogle(
context: Context,
auth: FirebaseAuth
) {
val rawNonce = UUID.randomUUID().toString()
val bytes = rawNonce.toByteArray()
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(bytes)
val hashedNonce = digest.fold("") { str, it ->
str + "%02x".format(it)
}
val googleIdOption: GetGoogleIdOption =
GetGoogleIdOption.Builder()
.setFilterByAuthorizedAccounts(true)
.setServerClientId(context.getString(R.string.web_client_id))
.setAutoSelectEnabled(true)
.setNonce(hashedNonce)
.build()
val googleSignRequest: GetCredentialRequest = GetCredentialRequest.Builder()
.addCredentialOption(googleIdOption)
.build()
val credentialManager = CredentialManager.create(context)
CoroutineScope(Dispatchers.IO).launch {
try {
val result = credentialManager.getCredential(
request = googleSignRequest,
context = context,
)
handleGoogleSignIn(context, auth, result)
} catch (e: GetCredentialException) {
handleGoogleSignInFailure(context, e)
}
}
}
private fun handleGoogleSignInFailure(context: Context, e: Exception) {
Log.e("TAG", "Unexpected error: ${e.message.toString()}")
postToastMessage("Google Login Failed: ${e.message.toString()}")
}
I fixed it by setting the setFilterByAuthorizedAccounts to false instead of true. When it's true it checks for any account the user has already logged into your app with. If the user has never logged in before with any of their Google accounts then it should be false.
val googleIdOption: GetGoogleIdOption =
GetGoogleIdOption.Builder()
.setFilterByAuthorizedAccounts(false)
.setServerClientId(context.getString(R.string.web_client_id))
.setAutoSelectEnabled(true)
.setNonce(hashedNonce)
.build()