[英]Django CSRF Protection Issue
我剛剛開始第一次使用 Django 構建 API,但在嘗試使用 Postman 測試端點時遇到了問題。當我向端點 http://localhost:8000/arithmetic/ 發送 POST 請求時包含以下 JSON:
{
"expression": "1 + 2 × 3"
}
我收到以下回復:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>403 Forbidden</title>
<style type="text/css">
html * {
padding: 0;
margin: 0;
}
body * {
padding: 10px 20px;
}
body * * {
padding: 0;
}
body {
font: small sans-serif;
background: #eee;
color: #000;
}
body>div {
border-bottom: 1px solid #ddd;
}
h1 {
font-weight: normal;
margin-bottom: .4em;
}
h1 span {
font-size: 60%;
color: #666;
font-weight: normal;
}
#info {
background: #f6f6f6;
}
#info ul {
margin: 0.5em 4em;
}
#info p,
#summary p {
padding-top: 10px;
}
#summary {
background: #ffc;
}
#explanation {
background: #eee;
border-bottom: 0px none;
}
</style>
</head>
<body>
<div id="summary">
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
</div>
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre>
CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a href="https://docs.djangoproject.com/en/4.1/ref/csrf/">Django’s
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function passes a <code>request</code> to the template’s <a
href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
method.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
<li>The form has a valid CSRF token. After logging in in another browser
tab or hitting the back button after a login, you may need to reload the
page with the form, because the token is rotated after a login.</li>
</ul>
<p>You’re seeing the help section of this page because you have <code>DEBUG =
True</code> in your Django settings file. Change that to <code>False</code>,
and only the initial error message will be displayed. </p>
<p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>
</body>
</html>
我不確定如何解決此問題以便我可以測試我的端點。
到目前為止,這是我的代碼:
在算術應用程序中:
意見.py:
import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
# Create your views here.
def parse_request(str):
if '×' in str:
str = str.replace('×', '*')
if '÷' in str:
str = str.replace('÷', '/')
def calculate(request):
if request.method == 'POST':
# parse the json object
body = json.loads(request.body)
expression = body['expression']
return JsonResponse({
'response': expression
})
else:
return JsonResponse({
'error': 'invalid request method'
})
網址.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.calculate)
]
我的主要項目 urls.py 如下所示:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('arithmetic/', include('arithmetic.urls'))
]
我的想法是將其連接到我已經開發的 React 前端,但我想在嘗試將其連接到前端之前自行測試端點以確保其正常工作。
任何幫助或指導將不勝感激。
解決此問題的最快方法是使用 Django 的csrf_exempt
function為您的視圖禁用 CSRF 保護。
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [path('', csrf_exempt(views.calculate))]
您也可以在視圖中使用裝飾器:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def calculate(request):
if request.method == 'POST':
# parse the json object
body = json.loads(request.body)
expression = body['expression']
return JsonResponse({
'response': expression
})
else:
return JsonResponse({
'error': 'invalid request method'
})
您還可以從配置文件中完全刪除中間件,這將禁用所有端點的 CSRF 保護。 從配置文件中,刪除此行:
django.middleware.csrf.CsrfViewMiddleware
注意:在大多數情況下不建議這樣做,因為它會使您的 API 容易受到 CSRF 攻擊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.