You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST Framework中CSRF验证失败请求终止问题求助

Hey there! Let's break down why you're running into that "CSRF verification failed" error even with JWT authentication set up in DRF, and how to fix it.

First, let's clarify: JSONWebTokenAuthentication from rest_framework_jwt doesn't automatically skip CSRF checks entirely. DRF still enforces CSRF protection for requests that come from browsers (like AJAX calls from your frontend) because it falls back to session-based auth if JWT isn't properly validated or sent. Here are the most common fixes:

1. Double-check your JWT request header

Make sure you're sending the JWT token in the Authorization header with the correct prefix. For rest_framework_jwt, the default prefix is JWT (not Bearer). Your request header should look like this:

Authorization: JWT <your-token-string>

If this header is missing or formatted incorrectly, DRF will ignore JWT auth and try to use session auth— which triggers the CSRF check.

2. Add CSRF token to browser-based requests

If your frontend is hosted on the same domain as your DRF backend (e.g., you're using Django templates to render pages and making AJAX calls), you need to include the CSRF token in your request headers:

  • Grab the CSRF token from either the Django form's csrfmiddlewaretoken input or the csrftoken cookie.
  • Include it in the X-CSRFToken header.

Example JavaScript code for an AJAX request:

// Get token from form input
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// OR get from cookie (if no form is present)
// function getCookie(name) {
//   let cookieValue = null;
//   if (document.cookie && document.cookie !== '') {
//       const cookies = document.cookie.split(';');
//       for (let i = 0; i < cookies.length; i++) {
//           const cookie = cookies[i].trim();
//           if (cookie.substring(0, name.length + 1) === (name + '=')) {
//               cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
//               break;
//           }
//       }
//   }
//   return cookieValue;
// }
// const csrftoken = getCookie('csrftoken');

// Send request with both JWT and CSRF tokens
fetch('/api/profile/create/', {
  method: 'POST',
  headers: {
    'Authorization': 'JWT ' + yourJwtToken,
    'X-CSRFToken': csrftoken,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(yourProfileData)
});

3. Exempt the view from CSRF checks (for pure API clients)

If your API is only intended for non-browser clients (like mobile apps, Postman, or third-party services), you can disable CSRF protection for this view entirely. Use the csrf_exempt decorator:

Option 1: Decorate the class view

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class createProfileView(generics.CreateAPIView):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes= [permissions.IsAuthenticated]
    parser_classes = (MultiPartParser, FormParser)

    # Rest of your view code...

Option 2: Decorate the route in urls.py

from django.views.decorators.csrf import csrf_exempt
from django.urls import path
from .views import createProfileView

urlpatterns = [
    path('profile/create/', csrf_exempt(createProfileView.as_view()), name='create-profile'),
]

⚠️ Note: Only use this if you're 100% sure you don't need CSRF protection— it's meant for API-only use cases where you're relying solely on JWT for auth.

4. Verify your request content-type

Your view uses MultiPartParser and FormParser, which handle form-data requests. If you're sending form data from a browser, DRF will trigger CSRF checks regardless of JWT. If possible, send JSON data with the Content-Type: application/json header— this helps DRF recognize it as an API request and reduces the likelihood of CSRF enforcement (though you still should follow the steps above for browser requests).

Quick recap

The most likely culprit is either a missing/misformatted JWT header, or a missing CSRF token in browser-based requests. Start by checking your request headers with a tool like Postman or browser dev tools to confirm everything is being sent correctly.

内容的提问来源于stack exchange,提问作者Tosin Ayoola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:12:50