首页 > 解决方案 > 如何在 django for android 中使用 google api 客户端创建帐户/登录

问题描述

我想实现与url 中给出的 Android Kotlin 相同的场景。

  1. 对于 Web 应用程序 ,我通过点击链接使用 google 为 Web 应用程序创建了登录名。这是我在views.py中用于访问令牌的 Google 登录视图(正如一位用户在此处解释的那样 )
class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter

正如我预期的那样,它对我有用。

  1. 对于现在的 Android 应用程序 ,不知何故我已经为这个谷歌场景管理了一个代码。这是我的 Google 客户端登录视图。查看.py代码
class GoogleClientView(APIView):
    def post(self, request):
        token = {'id_token': request.data.get('id_token')}
        print(token)

        try:
            # Specify the CLIENT_ID of the app that accesses the backend:
            idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
            print(idinfo)

            if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                raise ValueError('Wrong issuer.')

            return Response(idinfo)
        except ValueError as err:
            # Invalid token
            print(err)
            content = {'message': 'Invalid token'}
            return Response(content)

当我使用 IdToken 请求 POST 方法时,这将提供以下信息,当然我们需要这个。

{
 // These six fields are included in all Google ID Tokens.
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953",

 // These seven fields are only included when the user has granted the "profile" and
 // "email" OAuth scopes to the application.
 "email": "testuser@gmail.com",
 "email_verified": "true",
 "name" : "Test User",
 "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
 "given_name": "Test",
 "family_name": "User",
 "locale": "en"
}

到这里为止,一切对我来说都很好。但是在这里我想为使用上述信息的用户创建帐户/登录名,并且在创建帐户/登录名时需要一个密钥作为返回响应。下面我尝试过的

class GoogleClientView(APIView):
    permission_classes = [AllowAny]
    adapter_class = GoogleOAuth2Adapter
    callback_url = 'https://example.com/user/accounts/google/login/callback/'
    client_class = OAuth2Client

    def post(self, request):
        token = {'id_token': request.data.get('id_token')}
        print(token)

        try:
            # Specify the CLIENT_ID of the app that accesses the backend:
            idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
            print(idinfo)

            if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                raise ValueError('Wrong issuer.')

            return Response(idinfo)
        except ValueError as err:
            # Invalid token
            print(err)
            content = {'message': 'Invalid token'}
            return Response(content)

再次看来,它没有为用户创建任何帐户/登录名,也没有任何密钥响应。那么,对于创建帐户/登录,我该如何实现代码?

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

标签: djangodjango-rest-frameworkdjango-views

解决方案


推荐阅读