为什么我的 Python POST 有效,但我的 Java POST 出现 CSRF 错误?

Why does my Python POST work but my Java POST gives CSRF error?

我正在尝试发送一个 POST 和一些数据,我想为它创建一个应用程序,我有可用的 Python 代码,但在获取 Java 对应代码时遇到问题在职的。 Python:

headerpayload = {
        'X-Requested-With': 'XMLHttpRequest',
        'Host': host,
        'Origin': origin,
        'Referer': login_url,
        '__RequestVerificationToken': veri_token
    }

    payload = {
        "__RequestVerificationToken": veri_token,
        "Q_b9849eb2-813d-4d0a-a1ce-643f1c8af986_0": "test",
        "Q_62ebd8c8-7d45-481d-a8b1-ad54a390a029_0": "test@test.ca",
        "Q_f4a3bb2e-ebab-4660-a9a1-75c0d79fe0b4_0": "",
        "Q_20cd46d1-3b95-46ad-81a3-b7b4d7fe7bf9_0": "b9558536-87d3-4395-aceb-ac3e012b4bad",
        "Q_012d8ddf-e75a-4266-ae78-f59502862aa9_0": "Bay 4",
        "Q_6b61b457-f325-41d7-9784-5cb4a959223f_0": "Superman",
        "FormId": "276caa59-80a5-4ced-9b9d-025e1d753b4a",
        "_ACTION": "Continue",
        "PageIndex": "1"
    }

    result = session_requests.post(
    login_url,
    data=payload,
    headers=headerpayload
    )

Android: (OkHttp)

        
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("__RequestVerificationToken", veritoken)
                .addFormDataPart("Q_b9849eb2-813d-4d0a-a1ce-643f1c8af986_0", "test")
                .addFormDataPart("Q_62ebd8c8-7d45-481d-a8b1-ad54a390a029_0", "test@test.ca")
                .addFormDataPart("Q_f4a3bb2e-ebab-4660-a9a1-75c0d79fe0b4_0", "")
                .addFormDataPart("Q_20cd46d1-3b95-46ad-81a3-b7b4d7fe7bf9_0", "b9558536-87d3-4395-aceb-ac3e012b4bad")
                .addFormDataPart("Q_012d8ddf-e75a-4266-ae78-f59502862aa9_0", "Bay 4")
                .addFormDataPart("Q_6b61b457-f325-41d7-9784-5cb4a959223f_0", "Superman")
                .addFormDataPart("FormId", "276caa59-80a5-4ced-9b9d-025e1d753b4a")
                .addFormDataPart("_ACTION", "Continue")
                .addFormDataPart("PageIndex", "1")
                .build();
        Request request = new Request.Builder()
                .addheader("X-Requested-With", "XMLHttpRequest")
                .addheader("Host", host)
                .addheader("Origin", origin)
                .addheader("Referer", url)
                .addheader("__RequestVerificationToken", veritoken)


                .url(url)
                .post(requestBody)
                .build();

Python 代码工作正常,Java 代码不工作。

看起来您正在 python 代码中使用请求 python 库,它具有 cookie 持久性。但是,您在 Java 代码中的 post 请求似乎没有附加 CSRF cookie 令牌。您需要通过发出获取请求来获取 cookie,然后在发出 post 请求时添加 cookie。我将在下面展示一个使用 Jsoup 的示例。

Connection.Response r = Jsoup.connect(url).method(Connection.Method.GET).execute();
Map co = r.cookies();
Jsoup.connect(url).cookies(co).header(veriTokenKey, veritoken).data(veriTokenKey, veritoken).method(Connection.Method.POST).execute();