亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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/身份/登錄/網絡/后端身份驗證這是我的端點代碼?,F在我剛剛復制了應用程序生成的 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 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號