我有一个基本的Django服务器,它有一个python命令行客户机,可以投递到这个服务中。我有一个登录功能和一个post功能。尽管CSRF的cookie是从登录函数中设置的,但当我登录后尝试访问post_product端点时,服务器说是禁止的。
我已经对此进行了数日的故障排除,但没有任何运气。
/api/login/ function:
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
@csrf_exempt
def handle_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
if user.is_authenticated:
return HttpResponse(author.name + ' is logged in, Welcome!', status=201, content_type='text/plain')
return HttpResponse(data)
else:
return HttpResponse('disabled account', status=400, content_type='text/plain')
else:
return HttpResponse('invalid login', status=400, content_type='text/plain')
else:
return HttpResponse('request method invalid ' + request.method, status=400, content_type='text/plain')/api/postproduct/函数:
def post_story(request):
if request.method == 'POST' and request.user.is_authenticated:
# Pull product details from request.
# Validate product details.
# Create model and save.Python终端客户端
FAILURE_MESSAGE = "The server responded with an unsuccessful code: "
def run():
url ='http://127.0.0.1:8000' # For debugging
logged_in = false
with requests.session() as session:
while True:
command = input("""Enter one of the following commands:
login
post \n""")
# login case.
if command == "login":
url = user_inputs[1]
logged_in = login(session, url)
continue
# post case.
elif command == "post" and logged_in:
post(session, url)
continue
else:
print('incorrect command')
continue
def login(session, url):
username = input("Enter your username: \n")
password = input("Enter your password: \n")
response = session.post(url + "/api/login/", data={'username': username, 'password': password})
# If any response but success notify user.
if response.status_code != 201:
print(FAILURE_MESSAGE + str(response.status_code))
return False
else:
print("Successfully logged in!")
return True
def post(session, url):
# Check session is authenticated
if 'csrftoken' not in session.cookies:
print("Not authenticated, have you logged in to a service?")
return
# Omitted : prompt user for productname, category, price and details.
data = {'productname': productname, 'category': category, 'price': price, 'details': details}
data_json = json.dumps(data)
payload = {'json_payload': data_json}
if not session_is_active():
print("You aren't logged into any services")
return
else:
response = session.post(url + "/api/postproduct/", data=payload)
print(6)
if response.status_code != 201:
print(FAILURE_MESSAGE + str(response.status_code))
return
print("Post was successful")当我运行客户端时,登录可以正常工作,并且在检查时确实设置了csrf cookie。但是,当我试着发布时,服务器会用403进行响应。从服务器的输出:
[15/Aug/2019 15:45:23] "POST /api/login/ HTTP/1.1" 201 42
Forbidden (CSRF token missing or incorrect.): /api/postproduct/发布于 2019-08-15 15:55:54
Django的CSRF保护要求您将CSRF cookie和一个令牌隐藏在表单字段中。对于AJAX请求,您可以设置一个标头而不是表单字段。
尝试如下(未经测试)的内容:
headers = {'X-CSRFToken': session.cookies['csrftoken']}
response = session.post(url + "/api/postproduct/", data=payload, headers=headers)发布于 2020-09-23 08:16:07
Error = csrf禁忌(CSRF令牌丢失或不正确)。当向Django后端提交请求时:
在表单中,包含{% csrf_token %},它生成带有csrf令牌值的输入标记,并且在请求中,标头包含‘X’
headers: {
content_type: 'application/json',
'X-CSRFToken': "{{ csrf_token }}"
},https://stackoverflow.com/questions/57512446
复制相似问题