python - 在 Django 中验证 Google ID token

标签 python django react-native django-rest-framework google-signin

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

然后,我尝试将 ID token 发送到 Django + DRF 后端,以便对其进行验证并创建和/或登录相关的用户帐户。我按照此处的说明进行操作:https://developers.google.com/identity/sign-in/web/backend-auth

这是我的端点代码。现在我只是复制应用程序生成的 ID token 并通过 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 请求时,第一个打印语句将运行,确认 token 已正确接收。然而,第二个打印语句永远不会运行,我总是得到“无效 token ”响应。因此,我相信 verify_oauth2_token 不知何故失败了,但它没有给我更多信息。

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

最佳答案

在 friend 的帮助下自己解决了这个问题。只需更改异常处理以显示相关错误,然后传递 token['id_token'] 而不是完整的 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)

关于python - 在 Django 中验证 Google ID token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61187305/

相关文章:

python - 有没有办法使用 Paste Deploy 共享通用配置?

python - 在 numba 函数中创建一个新的列表/数组

mysql - 如何将 md5 函数应用于 django orm 中的字段?

javascript - 流量: "Cannot access computed property using undefined [1]" when using default props for functional react components

python - 如果子进程更改了系统时间,pexpect 会错误地超时

python - 如何在 tkinter ~ python 中放置在网格中的两个小部件之间添加空间?

python - ElementTree 实例没有属性 'fromstring' 。那么,我做错了什么?

javascript - Django,角色匹配查询不存在

html - 如何在 React Native 中对齐极左和极右的元素?

javascript - 具有独立状态的动态生成的复选框 React-Native