使用 django-rest-auth 在 Android 中登录 Google

Moh*_*nki 5 authentication django android oauth django-rest-auth

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

从android的文档:

获取后端服务器的 OAuth 2.0 客户端 ID 如果您的应用通过后端服务器进行身份验证或从后端服务器访问 Google API,则必须获取为您的服务器创建的 OAuth 2.0 客户端 ID。查找 OAuth 2.0 客户端 ID

根据我的理解,流程是:

  • Android 应用程序auth code将从 google获取将传递到后端。
  • 后端将获得access tokenauth code从Android应用程序和client secret
  • 通过acess token我们获取用户信息并access token保存在数据库中。

我的疑问是:

  1. 我在 StackOverflow 上的某个地方读到我们需要创建两个 OAuth 客户端,一个用于 Android,另一个用于 Web 应用程序。这是真的?
  2. Django Rest Auth Login View 需要redirect_url定义一个,但我不明白redirect_uri在 Android 设备的情况下会是什么,或者我们需要在auth code从 Google获取时传递这个 URL 。
  3. 在OAuth园地,我把我的后端的client idclient secret,得到了auth code,当我过了这个auth code给我的登录查看我得到的redirect_uri_mismatch,但如果我把redirect_url = 'developer.google.com'它的工作原理,我猜auth code包含从那里产生,这就是为什么这应该是一样的主机信息redirect_url在我的 rest-auth 视图中,那么对于 android 来说它应该是什么?

这是我的 Google 登录视图。

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

请询问更多信息如果我忘了放任何。

我正在使用这个 django-rest-auth

一些有用的链接 -

Moh*_*nki 4

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

  1. 是的,您需要两个客户端 ID,一个用于您的 Android 设备,一个用于您的 Web 应用程序。
  2. 只需在 GoogleLoginView 中添加http://localhost:8000/accounts/google/login/callback/并将callback_url其放入 Google 开发者控制台即可。
  3. 我不确切知道 Android 生成的身份验证代码是否包含任何主机信息,但似乎只要您在登录视图类和 google 开发人员控制台中添加的回调 URL 相同,它就可以工作。

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

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

注意:仅当您将身份验证代码传递到此视图时才需要callback_urland ,但如果您传递then ,则不需要。client_classaccess_tokencallback_urlclient_class