为了账号安全,请及时绑定邮箱和手机立即绑定

在 Django 中验证 Google ID 令牌

在 Django 中验证 Google ID 令牌

UYOU 2022-10-06 19:01:28
我有一个 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 登录,所以我完全有可能错过了一些明显的东西。将不胜感激任何帮助!
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

在朋友的帮助下自己解决了这个问题。只需更改异常处理以显示相关错误,然后传递 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)


查看完整回答
反对 回复 2022-10-06
  • 1 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号