首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从GoogleCredential迁移到GoogleCredentials,仍然可以访问People API?

如何从GoogleCredential迁移到GoogleCredentials,仍然可以访问People API?
EN

Stack Overflow用户
提问于 2021-05-12 09:03:41
回答 3查看 1.3K关注 0票数 6

背景

对于我正在开发的应用程序,它使用人员API使用凭证(用户登录)。一旦用户提供了凭证,我就可以访问各种Google,比如People API。一个例子是获取联系人列表的例子:

https://developers.google.com/people/api/rest/v1/people.connections/list

我注意到com.google.api.client.googleapis.auth.oauth2.GoogleCredential类已经被废弃了:

https://googleapis.dev/java/google-api-client/latest/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.html

问题所在

该应用程序的旧代码是基于一些旧的G+代码(这里),以达到通过谷歌帐户的联系人。下面是它最重要部分的一个片段,它会让我在迁移时遇到麻烦:

代码语言:javascript
运行
复制
object GoogleOuthHelper {
    @WorkerThread
    fun setUp(context: Context, serverAuthCode: String?): Services {
        val httpTransport: HttpTransport = NetHttpTransport()
        val jsonFactory = JacksonFactory.getDefaultInstance()
        // Redirect URL for web based applications. Can be empty too.
        val redirectUrl = "urn:ietf:wg:oauth:2.0:oob"
        // Exchange auth code for access token
        val tokenResponse = GoogleAuthorizationCodeTokenRequest(
            httpTransport, jsonFactory, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET,
            serverAuthCode, redirectUrl)
            .execute()
        // Then, create a GoogleCredential object using the tokens from GoogleTokenResponse
        val credential = GoogleCredential.Builder()
            .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .build()
        val accessToken = tokenResponse.accessToken
        getDefaultSecuredSharedPreferences(context).edit()
            .putString(SecuredSharedPreferences.KEY__GOOGLE_ACCESS_TOKEN, accessToken).apply()
        credential.setFromTokenResponse(tokenResponse)
        val appPackageName = context.packageName
        val peopleServiceApi = PeopleService.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(appPackageName)
            .build()
        val peopleService = peopleServiceApi.people()
        val otherContactsService = peopleServiceApi.otherContacts()
        val contactGroups = peopleServiceApi.contactGroups()
        return Services(peopleService, otherContactsService, contactGroups)
    }

    class Services(
        /**https://developers.google.com/people/api/rest/v1/people*/
        val peopleService: PeopleService.People,
        /**https://developers.google.com/people/api/rest/v1/otherContacts*/
        val otherContactsService: OtherContacts,
        /**https://developers.google.com/people/api/rest/v1/contactGroups*/
        val contactGroups: ContactGroups)
}

问题甚至从一开始就是:

GoogleCredentials似乎不接受我在GoogleCredential类中获得的任何高于它的内容。

要向其添加更多内容,该函数以"serverAuthCode“作为参数,这是来自GoogleSignInAccount的参数,但要获得它,我需要使用已废弃的GoogleApiClient类:

代码语言:javascript
运行
复制
        fun prepareGoogleApiClient(someContext: Context): GoogleApiClient {
            val context = someContext.applicationContext ?: someContext
            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestServerAuthCode(GOOGLE_CLIENT_ID)
                .requestEmail()
                .requestScopes(
                    Scope(PeopleServiceScopes.CONTACTS_READONLY),
                    Scope(PeopleServiceScopes.USERINFO_PROFILE),
                    Scope(PeopleServiceScopes.USER_EMAILS_READ),
                    Scope(PeopleServiceScopes.CONTACTS),
                    Scope(PeopleServiceScopes.CONTACTS_OTHER_READONLY)
                )
                .build()
            return GoogleApiClient.Builder(context)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build()
        }

我就是这么做的:

代码语言:javascript
运行
复制
val connectionResult = googleApiClient!!.blockingConnect()
if (!connectionResult.isSuccess)
    return
val operation = Auth.GoogleSignInApi.silentSignIn(googleApiClient)
val googleSignInResult: GoogleSignInResult = operation.await()
val googleSignInAccount = googleSignInResult.signInAccount
//use googleSignInAccount.serverAuthCode in setUp() function above

Gradle文件具有以下依赖关系:

代码语言:javascript
运行
复制
// https://mvnrepository.com/artifact/com.google.auth/google-auth-library-oauth2-http
implementation 'com.google.auth:google-auth-library-oauth2-http:0.26.0'
// https://github.com/googleapis/google-api-java-client-services/tree/master/clients/google-api-services-people/v1#gradle   https://mvnrepository.com/artifact/com.google.apis/google-api-services-people
implementation 'com.google.apis:google-api-services-people:v1-rev20210515-1.31.0'

我试过的

除了查看文档(没有看到类似于我必须处理的内容)之外,我尝试在这里写这方面的内容。

遗憾的是,我还无法找到如何从旧代码中迁移。

我试着在那里问我如何迁移(这里这里),但是还没有得到答案。

问题

如何在仍然使用各种API (如People API)的同时,从GoogleCredential迁移到GoogleCredentials

换句话说:我如何才能避免在Android上使用任何不推荐的类(GoogleCredential和GoogleApiClient),同时仍然能够使用各种API?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-06-08 14:58:43

如何在仍然使用各种API (如People API)的同时,从GoogleCredential迁移到GoogleCredentials? 换句话说:我如何才能避免在Android上使用任何不推荐的类(GoogleCredential和GoogleApiClient),同时仍然能够使用各种API?

虽然您可以让GoogleCredentials直接工作,但是最好使用从GoogleCredentials派生的类,比如UserCredentials,它可以像GoogleCredential那样支持令牌刷新。GoogleCredentials更像是一个基础类。

下面的代码使用了UserCredentials。这主要是您所介绍的,但为了演示的目的,我已经更改了一些凭据存储逻辑。除了startActivityForResult()之外,此代码没有不推荐的方法。

serverAuthCode可以从GoogleSignInAccount获得。看看通过GoogleApiClient关于如何消除对GoogleApiClient的依赖。我已经从Google信号快速启动中更新了我的公共要旨 of RestApiActivity,它展示了如何使用GoogleOauthHelper和GoogleApi。

GoogleOauthHelper.kt

代码语言:javascript
运行
复制
object GoogleOauthHelper {
    @WorkerThread
    fun setUp(context: Context, serverAuthCode: String?): Services {
        val httpTransport: HttpTransport = NetHttpTransport()
        val jsonFactory = GsonFactory.getDefaultInstance()
        // Redirect URL for web based applications. Can be empty too.
        val redirectUrl = "urn:ietf:wg:oauth:2.0:oob"

        // Patch for demo
        val GOOGLE_CLIENT_ID = context.getString(R.string.GOOGLE_CLIENT_ID)
        val GOOGLE_CLIENT_SECRET = context.getString(R.string.GOOGLE_CLIENT_SECRET)

        var accessToken: AccessToken? = null
        var refreshToken =
            getDefaultSecuredSharedPreferences(context).getString(
                SecuredSharedPreferences.KEY_GOOGLE_REFRESH_TOKEN,
                null
            )

        if (refreshToken == null) {
            /*  Did we lose the refresh token, or is this the first time? Refresh tokens are only
                returned the first time after the user grants us permission to use the API. So, if
                this is the first time doing this, we should get a refresh token. If it's not the
                first time, we will not get a refresh token, so we will proceed with the access
                token alone. If the access token expires (in about an hour), we will get an error.
                What we should do is to ask the user to reauthorize the app and go through the
                OAuth flow again to recover a refresh token.

                See https://developers.google.com/identity/protocols/oauth2#expiration regarding
                how a refresh token can become invalid.
            */
            val tokenResponse = GoogleAuthorizationCodeTokenRequest(
                httpTransport, jsonFactory, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET,
                serverAuthCode, redirectUrl
            ).execute()

            refreshToken = tokenResponse.refreshToken
            if (refreshToken != null) {
                getDefaultSecuredSharedPreferences(context).edit()
                    .putString(SecuredSharedPreferences.KEY_GOOGLE_REFRESH_TOKEN, refreshToken)
                    .apply()
            } else {
                Log.d("Applog", "No refresh token. Going with access token alone.")
                val expiresAtMilliseconds =
                    Clock.SYSTEM.currentTimeMillis() + tokenResponse.expiresInSeconds * 1000
                accessToken = AccessToken(tokenResponse.accessToken, Date(expiresAtMilliseconds))
            }
        }

        Log.d("Applog", "Refresh token: $refreshToken")
        // UserCredentials extends GoogleCredentials and permits token refreshing.
        val googleCredentials = UserCredentials.newBuilder().run {
            clientId = GOOGLE_CLIENT_ID
            clientSecret = GOOGLE_CLIENT_SECRET
            setRefreshToken(refreshToken)
            setAccessToken(accessToken)
            build()
        }

        // Save access token on change
        googleCredentials.addChangeListener { oAuth2Credentials ->
            saveAccessToken(oAuth2Credentials.accessToken)
        }

        val requestInitializer: HttpRequestInitializer = HttpCredentialsAdapter(googleCredentials)
        val appPackageName = context.packageName

        val peopleServiceApi = PeopleService.Builder(httpTransport, jsonFactory, requestInitializer)
            .setApplicationName(appPackageName)
            .build()

        return peopleServiceApi.run { Services(people(), otherContacts(), contactGroups()) }
    }

    private fun saveAccessToken(accessToken: AccessToken) {
        // Persist the token securely.
        Log.d("Applog", "Access token has changed: ${accessToken.tokenValue}")
    }

    // Warning insecure!: Patch for demo.
    private fun getDefaultSecuredSharedPreferences(context: Context): SharedPreferences {
        return PreferenceManager.getDefaultSharedPreferences(context)
    }

    // Warning insecure!: Patch for demo.
    object SecuredSharedPreferences {
        const val KEY_GOOGLE_REFRESH_TOKEN = "GOOGLE_REFRESH_TOKEN"
    }

    class Services(
        /**https://developers.google.com/people/api/rest/v1/people*/
        val peopleService: PeopleService.People,
        /**https://developers.google.com/people/api/rest/v1/otherContacts*/
        val otherContactsService: PeopleService.OtherContacts,
        /**https://developers.google.com/people/api/rest/v1/contactGroups*/
        val contactGroups: PeopleService.ContactGroups,
    )
}

我在演示项目上发了一个GitHub。

票数 1
EN

Stack Overflow用户

发布于 2022-06-16 08:37:14

有一个非常简单的解决方案,隐藏在谷歌的文档com.google.auth.http.HttpCredentialsAdapter中。它允许从新的com.google.api.client.http.HttpRequestInitializer创建一个com.google.auth.oauth2.GoogleCredentials,并使用它调用.Builder()构造函数。

简单的例子是:

代码语言:javascript
运行
复制
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.bigquery.Bigquery;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

Bigquery bq = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
    .setApplicationName(APPLICATION_NAME)
    .build();
票数 0
EN

Stack Overflow用户

发布于 2022-09-06 13:09:39

下面是在执行SignInIntent和接收GoogleSignInAccount之后,如何使用People API访问性别和生日

代码语言:javascript
运行
复制
private suspend fun handlePeopleApi(account: GoogleSignInAccount) {
    withContext(Dispatchers.IO) {
        val credential =
            GoogleAccountCredential.usingOAuth2(
                requireContext(),
                listOf(
                    PeopleServiceScopes.USER_GENDER_READ,
                    PeopleServiceScopes.USER_BIRTHDAY_READ
                )
            )
        credential.selectedAccountName = account.email

        val peopleService = PeopleService.Builder(NetHttpTransport(), GsonFactory(), credential)
            .setApplicationName(getString(R.string.app_name))
            .build()

        val person = peopleService.people()
            .get("people/${account.id}")
            .setPersonFields("birthdays,genders")
            .execute()

        Log.d("People API", "Person: ${person.birthdays}, ${person.genders}")
    }
}

我有以下这些等级依赖关系:

代码语言:javascript
运行
复制
implementation 'com.google.apis:google-api-services-people:v1-rev20220531-2.0.0'
implementation 'com.google.api-client:google-api-client-android:1.20.0'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67500479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档