在 Django 中验证 Google ID 令牌

Verifying a Google ID Token in Django

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

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

这是我的端点代码。现在我只是复制应用程序生成的 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 请求时,第一个打印语句运行确认令牌已正确接收。然而,第二个打印语句从未运行,我总是得到 'Invalid token' 响应。所以,我相信 verify_oauth2_token 以某种方式失败了,但它不再给我任何信息。

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

在朋友的帮助下自己解决了这个问题。只需更改异常处理以显示相关错误,然后传递 token['id_token'] 而不是完整的 token dict。新代码:

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)