Google 使用 django-rest-auth 登录 Android

Google Sign-in in Android with django-rest-auth

我一直在尝试在 Android 中添加 Google 登录,但有一些疑问。 来自 Android 文档 Integrate google sign in android 在服务器端身份验证部分 Client Id 是必需的,它是后端服务器的 OAuth 2.0 Web 应用程序 client ID

来自 android 的文档:

Get your backend server's OAuth 2.0 client ID If your app authenticates with a backend server or accesses Google APIs from your backend server, you must get the OAuth 2.0 client ID that was created for your server. To find the OAuth 2.0 client ID

根据我的理解,流程是:

我的疑惑是:

  1. 我在 Whosebug 的某处读到我们需要创建两个 OAuth 客户端,一个用于 Android,一个用于 Web 应用程序。这是真的吗?
  2. Django Rest Auth Login View 需要定义一个 redirect_url,但我不明白 Android 设备的 redirect_uri 是什么,或者我们需要传递这个URL 从 Google.
  3. 获取 auth code
  4. 在 OAuth Playground 上,我将后端的 client idclient secret 放入 auth code,当我将此 auth code 传递到我的登录视图时,我得到了 redirect_uri_mismatch 但如果我输入 redirect_url = 'developer.google.com' 它有效,我猜 auth code 包含生成它的主机信息,这就是为什么这应该与我的 rest-auth 中的 redirect_url 相同查看,然后 android 它应该是什么?

这是我的 Google 登录视图。

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client
    callback_url = 'localhost:8000' # What this should be?

如有遗忘请追问

我正在用这个 django-rest-auth

有些帮助link -

所以最后,我想通了,回答我自己的问题,这样有人可能会觉得这有帮助。

  1. 是的,您需要两个客户端 ID,一个用于 Android 设备,一个用于 Web 应用程序。
  2. 只需在 GoogleLoginView 中将 http://localhost:8000/accounts/google/login/callback/ 添加为 callback_url,并将其放入您的 Google 开发者控制台。
  3. 我不知道 Android 生成的授权码是否包含任何主机信息,但似乎只要你在登录视图中添加的回调 URL class 和 google 开发者控制台是一样的。

您的 Google 登录视图应如下所示。

class GoogleLogin(SocialLoginView):
    authentication_classes = (JSONWebTokenAuthentication,)
    adapter_class = GoogleOAuth2Adapter
    callback_url = 'http://localhost:8000/accounts/google/login/callback/'
    client_class = OAuth2Client

Note: You only need callback_url and client_class in case where you are passing the auth code to this view but if in you are passing the access_token then callback_url and client_class is not necessary.