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

使用Credential Manager获取Google ID Token后,如何添加Drive API权限域并获取访问令牌?

为Credential Manager添加Drive API权限域并获取访问令牌

步骤1:添加Drive API权限域

先根据业务需求选择合适的Drive API权限范围,常用选项包括:

  • https://www.googleapis.com/auth/drive.file:仅访问用户通过你的应用创建/打开的文件
  • https://www.googleapis.com/auth/drive.readonly:只读访问用户Drive中的所有文件

在构建GetGoogleIdOption时,通过setScopes方法注入这些权限域,让用户授权时同步申请Drive访问权限。

步骤2:修改代码以获取访问令牌

调整原代码,添加权限域配置,并新增对GoogleOAuth2Credential的处理逻辑,从中提取访问令牌:

suspend fun saveGoogleCredentials(context: Context, nonce: String): Pair<CredentialManagerExceptions?, GoogleIdTokenCredential?> {
    if (!this::serverClientID.isInitialized) {
        return Pair(
            CredentialManagerExceptions(
                code = 503,
                message = "Google client is not initialized yet",
                details = "Check if Google credentials is provided"
            ), null
        )
    }

    // 注入Drive API权限域
    val driveScopes = listOf("https://www.googleapis.com/auth/drive.file")
    val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
        .setFilterByAuthorizedAccounts(false)
        .setNonce(nonce)
        .setServerClientId(serverClientID)
        .setScopes(driveScopes)
        .build()

    val request: GetCredentialRequest = GetCredentialRequest.Builder()
        .addCredentialOption(googleIdOption)
        .build()

    Log.d("CredentialManager", "$request")
    val result = credentialManager.getCredential(
        request = request,
        context = context,
    )

    when (val credential = result.credential) {
        is CustomCredential -> {
            return when (credential.type) {
                GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL -> {
                    try {
                        val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
                        Pair(null, googleIdTokenCredential)
                    } catch (e: GoogleIdTokenParsingException) {
                        Pair(
                            CredentialManagerExceptions(
                                code = 501,
                                message = "Received an invalid google id token response",
                                details = e.localizedMessage,
                            ), null
                        )
                    }
                }
                // 处理OAuth2凭证,提取访问令牌
                GoogleOAuth2Credential.TYPE_GOOGLE_OAUTH2_CREDENTIAL -> {
                    try {
                        val googleOAuth2Credential = GoogleOAuth2Credential.createFrom(credential.data)
                        val accessToken = googleOAuth2Credential.accessToken
                        // 此处可将accessToken保存或直接用于Drive API请求
                        Log.d("DriveAccessToken", accessToken)
                        // 可根据业务需求调整返回逻辑,比如同时返回ID Token和访问令牌
                        Pair(null, null)
                    } catch (e: GoogleOAuth2CredentialParsingException) {
                        Pair(
                            CredentialManagerExceptions(
                                code = 504,
                                message = "Failed to parse Google OAuth2 credential",
                                details = e.localizedMessage,
                            ), null
                        )
                    }
                }
                else -> {
                    Pair(
                        CredentialManagerExceptions(
                            code = 502,
                            message = "Invalid request",
                            details = null
                        ), null
                    )
                }
            }
        }
        else -> {
            return Pair(
                CredentialManagerExceptions(
                    code = 502,
                    message = "Invalid request",
                    details = null
                ), null
            )
        }
    }
}

关键修改说明

  • 在GetGoogleIdOption构建时添加setScopes(driveScopes),指定Drive API权限域
  • 新增对GoogleOAuth2Credential类型凭证的处理逻辑,从中提取accessToken
  • 新增GoogleOAuth2CredentialParsingException捕获,处理凭证解析失败场景

注意事项

  • 确保Google Cloud项目已启用Drive API
  • 在OAuth同意屏幕中添加使用的Drive权限域,否则用户授权会报错
  • 访问令牌有有效期限制,若需长期访问,可利用GoogleOAuth2Credential中的refreshToken刷新令牌

内容的提问来源于stack exchange,提问作者Sunil Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:53:35