禁止 (403) CSRF 验证失败。请求被中止。使用 Google OAuth2

问题描述 投票:0回答:1

使用 React 和 Django 后端来归档我的应用程序前端: 我的 React 前端应用程序和 django 后端应用程序有以下文件:

// Router.jsx
import { createBrowserRouter, Navigate, RouterProvider } from 'react-router-dom'
import { useEffect } from 'react'
import { Home } from '@pages/Home'
import { Error } from '@pages/Error'
import { NotFound } from '@pages/NotFound'

export const Router = () => {
  const google = window.google

  const handleCallbackResponse = (response) => {
    console.log(response)
    const authorizationCode = response.credential
    if (authorizationCode) {
      console.log('Authorization code:', authorizationCode)
      fetch('http://localhost:8000/auth/google/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code: authorizationCode })
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.json()
        })
        .then(data => {
          console.log('Response from Django backend:', data)
        })
        .catch(error => {
          console.error('There was an error with the fetch operation:', error)
        })
    }
  }

  useEffect(() => {
    google.accounts.id.initialize({
      client_id: 'No la pongo por seguridad',
      callback: handleCallbackResponse
    })

    google.accounts.id.renderButton(document.getElementById('signInButton'), {
      theme: 'outline',
      size: 'large'
    })
  }, [])

  const router = createBrowserRouter([
    {
      path: '/',
      element: <Navigate to='/home' />,
      errorElement: <Error />
    },
    {
      path: '/home',
      element: <Home />,
      errorElement: <Error />
    },
    {
      path: '*',
      element: <NotFound />
    }
  ])

  return (
    <>
      <RouterProvider router={router} />
    </>
  )
}
# views.py
from django.http import JsonResponse
import requests
def google_auth_callback(request):
    if request.method == 'POST':
        authorization_code = request.POST.get('code')
        google_token_endpoint = 'https://accounts.google.com/o/oauth2/'
        google_client_id = ''
        google_client_secret = ''
        redirect_uri = 'http://localhost'
        token_data = {
            'code': authorization_code,
            'client_id': google_client_id,
            'client_secret': google_client_secret,
            'redirect_uri': redirect_uri,
            'grant_type': 'authorization_code',
        }
        try:
            response = requests.post(google_token_endpoint, data=token_data)
            response.raise_for_status()
            google_response_data = response.json()
            access_token = google_response_data.get('access_token')
            return JsonResponse({'access_token': access_token}, status=200)
        except requests.exceptions.RequestException as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

Soy principiante en ambas tecnologias y si alguien ve algo mal en mi codigo aademas de mi error que me esta dando el“Forbidden (403) CSRF 验证失败。请求中止。”不,他访问了谷歌授权主题的许多材料,以及市长的材料,但它是安全的,并且已经过时了。 我是这两种技术的初学者,如果有人在我的代码中发现除了我的错误之外的其他错误,它会给我“禁止(403)CSRF验证失败。请求中止”。我还没有看到太多关于 Google 身份验证主题的材料,并且大多数现有材料都不是很安全或已被弃用。

他可能会在 que renderizo el boton 中包含 cambiar de la manera en la que renderizo el boton,poner una statement para ignorar los tokens (me dio otro error),y en General he echo de todo tipo de soluciones y ninguna me ha funcionado porque como digo todo el contenido de esto ya esta deprecado。 El google client id y google client Secret no los coloco por seguridad pero en mi app si estan puestos。 我什至尝试改变渲染按钮的方式,放置一个声明来忽略令牌(这给了我另一个错误),总的来说,我尝试了各种解决方案,但没有一个有效,因为正如我所说,所有This 的内容已被弃用。出于安全原因,我没有设置 Google 客户端 ID 和 Google 客户端密钥,但它们是在我的应用程序中设置的。

reactjs django oauth-2.0 google-oauth django-authentication
1个回答
0
投票

对于每个接收数据的处理程序

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def google_auth_callback(request):
    ...
© www.soinside.com 2019 - 2024. All rights reserved.