首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django服务器403 (CSRF令牌丢失或不正确)

问Django服务器403 (CSRF令牌丢失或不正确)
EN

Stack Overflow用户
提问于 2019-08-15 15:50:27
回答 2查看 2K关注 0票数 0

我有一个基本的Django服务器,它有一个python命令行客户机,可以投递到这个服务中。我有一个登录功能和一个post功能。尽管CSRF的cookie是从登录函数中设置的,但当我登录后尝试访问post_product端点时,服务器说是禁止的。

我已经对此进行了数日的故障排除,但没有任何运气。

/api/login/ function:

代码语言:javascript
复制
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/函数:

代码语言:javascript
复制
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终端客户端

代码语言:javascript
复制
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进行响应。从服务器的输出:

代码语言:javascript
复制
[15/Aug/2019 15:45:23] "POST /api/login/ HTTP/1.1" 201 42
Forbidden (CSRF token missing or incorrect.): /api/postproduct/
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-15 15:55:54

Django的CSRF保护要求您将CSRF cookie和一个令牌隐藏在表单字段中。对于AJAX请求,您可以设置一个标头而不是表单字段。

尝试如下(未经测试)的内容:

代码语言:javascript
复制
headers = {'X-CSRFToken': session.cookies['csrftoken']}
response = session.post(url + "/api/postproduct/", data=payload, headers=headers)
票数 1
EN

Stack Overflow用户

发布于 2020-09-23 08:16:07

Error = csrf禁忌(CSRF令牌丢失或不正确)。当向Django后端提交请求时:

在表单中,包含{% csrf_token %},它生成带有csrf令牌值的输入标记,并且在请求中,标头包含‘X’

代码语言:javascript
复制
headers: {
                content_type: 'application/json',
                'X-CSRFToken': "{{ csrf_token }}"
            },
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57512446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档