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

Django类视图作为webhook时出现Referer校验失败Forbidden报错

Django类视图webhook接口CSRF Forbidden报错解决方案

你遇到的Forbidden (Referer checking failed - no Referer.): /gc_callback/报错,是Django默认的CSRF校验拦截了无来源头、无CSRF token的第三方webhook请求。你之前直接给dispatch方法加csrf_exempt不生效,是因为Django类视图的方法不能直接使用函数装饰器,需要搭配method_decorator封装,或者直接在路由层配置CSRF豁免。

两种可行的解决方案如下:

方案1:类视图dispatch方法正确添加装饰器

导入method_decorator对csrf_exempt进行封装后再挂载到dispatch方法上,示例代码:

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

class Webhook(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(Webhook, self).dispatch(*args, **kwargs)
    
    # 后续补充你的请求处理逻辑,例如post方法
    def post(self, request, *args, **kwargs):
        # 处理webhook回调逻辑
        pass

方案2:路由层配置CSRF豁免(你实测生效的方案)

不需要修改类视图代码,直接在urls.py中给视图挂载csrf_exempt即可,示例配置:

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

urlpatterns = [
    path('gc_callback/', csrf_exempt(Webhook.as_view()), name='gc_callback'),
]

注:第三方webhook请求默认不会携带你站点的CSRF cookie和token,必须配置CSRF豁免才能正常接收回调,两种方案任选其一即可,路由层配置优先级更高,适合无需修改视图代码的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:54:01