我想使用“GoogleIdTokenCredential”创建登录系统。 但问题是有时
googleIdTokenCredential.id
返回整数,而 googleIdTokenCredential.displayName
返回空值。
但根据文档 getId() 应该返回一个 NonNull 字符串。
文档说:
public final @NonNull String getId()
与用户的 Google 帐户关联的电子邮件地址。
在build.gradle中
dependencies {
// dependencies for credential
implementation("androidx.credentials:credentials-play-services-auth:1.2.2")
implementation("com.google.android.libraries.identity.googleid:1.1.1")
}
在片段中
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val googleIdOption by lazy {
GetGoogleIdOption.Builder().setFilterByAuthorizedAccounts(false)
.setServerClientId("1071802491305-ndpjon6q72bu83phuo8dmmhuanvp2uki.apps.googleusercontent.com")
.setAutoSelectEnabled(true).setNonce(generateNonce()).build()
}
val request: androidx.credentials.GetCredentialRequest =
androidx.credentials.GetCredentialRequest.Builder().addCredentialOption(googleIdOption)
.build()
val mContext = requireContext()
val credentialManager by lazy { androidx.credentials.CredentialManager.create(mContext) }
lifecycleScope.launch {
try {
val result = credentialManager.getCredential(
request = request,
context = mContext,
)
handleSignIn(result)
} catch (e: androidx.credentials.exceptions.GetCredentialException) {
showMessage("Failed to get credential: $e")
}
}
}
private fun handleSignIn(result: androidx.credentials.GetCredentialResponse) {
when (val credential = result.credential) {
is CustomCredential -> {
if (credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
try {
val googleIdTokenCredential =
GoogleIdTokenCredential.createFrom(credential.data)
val id = googleIdTokenCredential.id
val displayName = googleIdTokenCredential.displayName
if (displayName == null) {
showMessage("Login Failed\nid: $id")
return
}
} catch (e: GoogleIdTokenParsingException) {
showMessage("Received an invalid google id token response, $e")
}
}
}
else -> {
showMessage("Unexpected type of credential")
}
}
}
private fun generateNonce(): String {
val nonceBytes = ByteArray(16)
SecureRandom().nextBytes(nonceBytes)
return Base64.encodeToString(
nonceBytes, Base64.NO_PADDING or Base64.NO_WRAP or Base64.URL_SAFE
)
}
private fun showMessage(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
我在谷歌搜索引擎和堆栈溢出上对此进行了很多搜索,但没有找到任何答案。 即使问“人工智能”也得不到正确答案。
请注意下面的屏幕记录,根据代码我应该获取googleIdTokenCredential.id的字符串(gmail)输出,但我得到的是整数。
你是对的。 googleIdTokenCredential.getID() 应该返回用户的电子邮件地址。
Google 已发现该问题并将很快纠正。