首页 > 解决方案 > 获取 Google 照片列表返回 401 未经身份验证

问题描述

我正在开发一个能够显示来自 Google 照片的图像的应用程序。

问题

当用户在Gmail Permission中手动撤销我的应用程序时,就会出现问题。用户执行此操作(撤销权限)后,再次打开应用程序,当应用程序尝试访问 Google 照片中的图像列表时,这是我在 JSON 中收到的错误。

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

之后我所做的就是退出并撤销 Google 登录。我再次登录,出现了选择 Gmail 帐户的弹出窗口,但没有出现授予应用程序权限弹出窗口。它应该出现,以便应用程序可以要求用户再次允许权限。

授予应用权限弹出窗口。 在此处输入图像描述

这是我如何使用 Google 登录

val googleSignInOptions =
    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(Scope("https://www.googleapis.com/auth/photoslibrary.readonly"))
        .requestEmail()
        .build()
val googleSignInClient = GoogleSignIn.getClient(context, googleSignInOptions!!)

这是我在代码中退出和撤销的方式

googleSignInClient?.signOut()
    ?.addOnCompleteListener {
        //Sign Out Complete
        googleSignInClient?.revokeAccess()?.addOnCompleteListener {
            //Revoke Complete
        }
    }

我的观察

  1. 即使在Gmail 权限页面中已经撤销了权限,GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(context), Scope(GOOGLE_PHOTOS_READ_SCOPE))仍然返回 true。从逻辑上讲,它应该返回 false,因为用户已经撤销了权限。
  2. 即使应用程序已经从谷歌登录中退出,当用户再次登录时,用户将获得与前一个相同的访问令牌,前提是到期时间仍在 1 小时内。

一天结束时,即使在用户手动撤销权限后,我也希望能够显示授予应用程序权限。谢谢你。

标签: androidgoogle-apigoogle-signingoogle-photos

解决方案


I have found a solution to this problem.

When logout, I need to clear the token by calling this function in a thread.

GoogleAuthUtil.clearToken(
    context,
    token
)

As overall, this is how I sign out.

googleSignInClient.signOut()
    .addOnCompleteListener {
        if (it.isSuccessful) {
            thread {
                GoogleAuthUtil.clearToken(
                    context,
                    token
                )
                googleSignInClient.revokeAccess()
            }
        }
        callBack(it.isSuccessful)
    }

推荐阅读