Android应用获取Web后台离线访问权限时出现redirect_uri_mismatch错误如何处理?

how to handle redirect_uri_mismatch error when Android app obtains offline access for Web back-end?

我想实现这个问题中描述的流程:

Authenticating with OAuth2 for an app *and* a website

Google 此处描述了此要求的解决方案:

https://developers.google.com/identity/protocols/CrossClientAuth#offlineAccess

我遵循了本指南,但不幸的是,当我在后端使用授权代码访问令牌并从 google 刷新令牌时,google 抛出此错误:

{
  "error": "invalid_request",
  "error_description": "Missing parameter: redirect_uri"
}

redirect_uri 对这种情况没有意义,因为客户端是 android.

还有一些建议,他们说使用 "postmessage" 作为重定向 uri 或使用 http://localhost 作为重定向 uri 或在 google 应用程序控制台的重定向 URI 中添加服务器地址,但是none 适用于此流程。

我花了很多时间来解决这个问题,这个工具 (https://developers.google.com/oauthplayground) 是由 google 提供的,这让我更想念领导,因为它是为主要的网络流程设计的,并且已经生成了访问令牌这个工具是不同的,需要重定向 uri。 (即使使用不记名令牌类型并使用客户端 ID 和密码) 毕竟我使用空字符串(“”)作为重定向url,最后我成功地通过服务器端获得了访问令牌。

空白应该有效,或者您也可以使用已安装的应用程序重定向 URI:'urn:ietf:wg:oauth:2.0:oob' - 参见 https://developers.google.com/identity/protocols/OAuth2InstalledApp

花了两天时间研究了Whosebug和google上的几乎所有问题,然后深入研究了AppAuth库(https://openid.github.io/AppAuth-iOS/ and https://openid.github.io/AppAuth-Android/),终于找到了答案。

所以,我发现了两条规则:

  1. redirect_uri 应该是以下之一:

    • 您的应用 bundle_idpackage_name + :/:// + *your_path*(例如 com.example.myapp://google_auth
    • 您的 client_id 反向 DNS 形式 + :/:// + *your_path*(例如 com.googleusercontent.apps.*account_id*:/my_path
  2. redirect_uri 初始授权码请求 (https://accounts.google.com/o/oauth2/v2/auth) 和授权码交换请求 (https://www.googleapis.com/oauth2/v4/token) 必须 完全相同