簡體   English   中英

Ajax中的CSRF令牌-Post Api

[英]CSRF Token in Ajax - Post Api

我的問題是我使用Django制作了POST API,我在按鈕上調用了該API。 但是每次它給CSRF令牌錯誤。 每次郵寄請求返回403。我不知道我要去哪里。

我在下面寫下我的代碼。 其余代碼可在此倉庫中找到。

views.py中的API

class UserList(APIView):

def post(self, request, format=None):
    serializer = User.objects.create()
    serializer = UserSerializer(data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

這是我在AJAX中進行的API調用

// CSRF Token ERROR
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');

//Function for the Post Api Call
var data = '{"inputs":[{"data":{"name":{"email"::{"msg"::{"enc_msg"}}}]}'
$("encrypt_button").on("click", function(e){
e.preventDefault();
$.ajax({
    'type': 'POST',
    'url': '/users',
    'data': {
        'csrfmiddlewaretoken' : csrftoken,
        'data': data,
    },
    success: function (response) {
        console.log("HIGH");
        console.log(response.outputs);
    },
    error: function (xhr) {
        console.log("HIGH");
        console.log(xhr);
    }
})
})

這在我的Urls.py中

urlpatterns = [
url('users', views.UserList.as_view()),
url('', main_view)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

這是我的index.html

{% load staticfiles %}

<!DOCTYPE html>
<html lang="en-Us">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Vignere Cypher</title>
</head>

<body>

<div class="container">
    <h1>Vignere Cypher</h1>


    <div class="main">
    <form class="main" method="post">
        {% csrf_token %}
        <div class="name">
            <label for="name">Your Name: </label>
            <input id="name" type="text" name="name" value="{{ name }}">
        </div>
        <div class="email">
            <label for="email">Email (To whom you want to send this message): </label>
            <input id="email" type="text" name="email" value="{{ email }}">
        </div>
        <div class="message">
            <label for="message" id="lol">Message to Encrypt: </label>
            <textarea rows="5" cols="50" id="message" type="text" name="message" value="{{ message }}"></textarea>
        </div>
        <div class="key_input">
            <label id="lol3" for="key">Enter the key:</label>
            <textarea rows="1" cols="30" type="text" name="key" placeholder="Enter key" id="key_input" /></textarea>
            <input type="button" value=" Encrypt " id="encrypt_button" onclick="doCrypt(false);UserAction();">
            <input type="button" value=" Decrypt " id="encrypt_button1" onclick="doCrypt(true)">
            <input type="button" value=" Random Key " id="encrypt_button2" onclick="">
        </div>
        <div class="enc_message">
            <label for="enc_message" id="lol1">Encrypted Message: </label>
            <textarea rows="5" cols="50" id="enc_message" type="text" name="enc_message" value="{{ enc_message }}"></textarea>
        </div>
        <input type="submit" value="Submit">

    </div>
    </form>
</div>
<script type="text/javascript" src="{% static 'main.js' %}"> </script>
</html>

更新資料

在嘗試以下給出的解決方案后,錯誤有所不同。 現在,發出一個get請求而不是發布。

圖片

直接取自Django文檔( https://docs.djangoproject.com/en/1.11/ref/csrf/ ):

 // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); 

如果在您的設置模塊中將CSRF_USE_SESSION設置為False,則以上函數用於獲取CSRF令牌。 如果此設置設置為True,則可以使用上面鏈接的文檔中找到的其他解決方案。

您在API調用中的數據缺少'csrfmiddlewaretoken' : csrftoken ,其中var csrftoken = getCookie('csrftoken'); 定義如下

function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

在定義上述`之后,將'csrfmiddlewaretoken' : csrftoken添加到您var data = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM