You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从旧版Google Auth迁移到CredentialManager后如何获取登录用户信息

Credential Manager 实现登录状态检查与上次登录账户信息获取

1. 检查登录状态并获取上次登录账户

在Credential Manager中,替代旧版GoogleSignIn.getLastSignedInAccount()的方式是通过retrieveCredential()方法获取已保存的授权凭据。若存在已登录账户,该方法会返回对应Credential;若没有,则抛出NoCredentialException,以此判断用户登录状态。

示例代码(Kotlin):

import androidx.credentials.CredentialManager
import androidx.credentials.GetGoogleIdOption
import androidx.credentials.RetrieveCredentialRequest
import androidx.credentials.exceptions.NoCredentialException
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.google.android.libraries.identity.googleid.GoogleIdTokenVerifier
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

// 初始化CredentialManager
val credentialManager = CredentialManager.create(context)

// 构建获取已授权Google账户的请求
val retrieveRequest = RetrieveCredentialRequest.Builder()
    .addCredentialOption(
        GetGoogleIdOption.Builder()
            .setFilterByAuthorizedAccounts(true) // 仅获取已授权过的账户(即上次登录的账户)
            .build()
    )
    .build()

// 异步获取凭据
CoroutineScope(Dispatchers.Main).launch {
    try {
        val result = credentialManager.retrieveCredential(retrieveRequest)
        val credential = result.credential
        
        // 转换为GoogleIdTokenCredential以提取用户信息
        if (credential is GoogleIdTokenCredential) {
            // 提取对应旧版的用户信息
            val email = credential.id // 对应旧版GoogleSignInAccount.getEmail()
            val displayName = credential.displayName // 对应getDisplayName()
            val photoUrl = credential.profilePictureUri // 对应getPhotoUrl()
            
            // 获取用户唯一ID(对应旧版getId()),需解析ID Token
            val idTokenVerifier = GoogleIdTokenVerifier.Builder(context)
                .setAudience(listOf("你的客户端ID")) // 替换为你的Google OAuth客户端ID
                .build()
            val googleIdToken = idTokenVerifier.verify(credential.idToken)
            val userId = googleIdToken?.payload?.subject
        }
    } catch (e: NoCredentialException) {
        // 无已登录账户,需引导用户登录
    } catch (e: Exception) {
        // 处理其他异常(如网络错误、验证失败等)
    }
}

2. 字段对应关系说明

旧版GoogleSignInAccount方法CredentialManager中获取方式
getEmail()GoogleIdTokenCredential.id
getDisplayName()GoogleIdTokenCredential.displayName
getPhotoUrl()GoogleIdTokenCredential.profilePictureUri
getId()(用户唯一ID)解析GoogleIdTokenCredential.idToken的payload中的subject字段
getIdToken()GoogleIdTokenCredential.idToken

注意事项

  • 需确保项目已配置好Credential Manager依赖及Google OAuth客户端ID。
  • 解析ID Token时,必须使用与登录流程一致的客户端ID验证,避免安全风险。

内容的提问来源于stack exchange,提问作者axita.savani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:31:08