Django - 没有令牌的帖子没有 CSRF 错误

问题描述

我正在使用 Django 来托管 React 应用程序。我在 Django 中添加了 CSRF 保护中间件。我尝试通过使用 Postman 发送 http 帖子来测试它,但标题中没有 x-csrftoken。令我惊讶的是,我没有得到 403,但我能够在没有 x-csrftoken 的情况下获取数据。这怎么可能? 您可以在下面找到我的 CSRF 设置。我的额外 Django 设置非常简单,包括 CORS。

...
# Cross Origin Resource Sharing Protection
CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
# Cross Site Request Forgery Protection
CSRF_TRUSTED_ORIGINS = []
MIDDLEWARE = [
    ...
    'django.middleware.csrf.CsrfViewMiddleware',]

解决方法

如果您使用的不是 SessionAuthentication CSRF will be disabled。在the docs