在 Django 中验证 Google ID 令牌

我有一个 React Native Android 应用程序,它使用 Google 登录来获取用户个人资料和电子邮件信息并生成一个 ID 令牌(使用https://github.com/react-native-community/google-signin)。登录有效,我在应用程序上显示用户名、电子邮件、照片等。


然后,我尝试将 ID 令牌发送到 Django + DRF 后端,以便对其进行验证并创建和/或登录相关的用户帐户。我按照此处的说明进行操作:https ://developers.google.com/身份/登录/网络/后端身份验证


这是我的端点代码。现在我刚刚复制了应用程序生成的 ID 令牌并通过 Postman 将其发送到后端。


class GoogleView(APIView):

    def post(self, request):

        token = {'idToken': request.data.get('idToken')}

        print(token)


        try:

            idinfo = id_token.verify_oauth2_token(token, requests.Request(), MY_APP_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:

            # Invalid token

            content = {'message': 'Invalid token'}

            return Response(content)

当我发送 POST 请求时,第一个打印语句运行确认令牌已正确接收。然而,第二个打印语句永远不会运行,我总是得到“无效令牌”响应。所以,我相信 verify_oauth2_token 以某种方式失败,但它不再给我信息。


我以前从未使用过 Google 登录,所以我完全有可能错过了一些明显的东西。将不胜感激任何帮助!


UYOU
浏览 168回答 1
1回答

子衿沉夜

在朋友的帮助下自己解决了这个问题。只需更改异常处理以显示相关错误,然后传递 token['id_token'] 而不是完整的令牌字典。新代码:class GoogleView(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(), MY_APP_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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python