Cross-Site Request Forgery (CSRF) tokens secure applications against unauthorized commands issued on behalf of authenticated users. Embedding a CSRF token in requests ensures they originate from a legitimate source rather than a malicious site.

To handle CSRF-protected workflows, first retrieve the token from the HTML or cookies, then include it in POST requests. This confirms the server recognizes the request as genuine, preventing tampering.

Combining cURL with parsing tools allows automating the token retrieval and injection process. By mimicking browser actions, cURL can manage authentication, form submissions, and other CSRF-guarded activities.

Steps to extract and use CSRF tokens with cURL:

  1. Open a terminal.
  2. Fetch the page containing the CSRF token and save cookies.
    $ curl --cookie-jar cookies.txt "https://www.example.com/login"
    <html><form><input type="hidden" name="csrf_token" value="12345abcde"></form></html>

    --cookie-jar stores cookies returned by the server.

  3. Extract the CSRF token from the response using tools like grep or sed.
    $ TOKEN=$(curl "https://www.example.com/login" | grep -oP 'name="csrf_token" value="\K[^"]+')
    $ echo $TOKEN
    12345abcde

    Adjust the pattern to match the token’s HTML structure.

  4. Send a POST request including the CSRF token and cookies.
    $ curl --cookie cookies.txt --data "username=user&password=pass&csrf_token=$TOKEN" "https://www.example.com/authenticate"
    HTTP/1.1 200 OK

    Use --data to include form fields such as the CSRF token.

  5. Verify success by inspecting the response.
    $ curl --cookie cookies.txt --data "username=user&password=pass&csrf_token=$TOKEN" "https://www.example.com/authenticate" --verbose

    --verbose confirms correct form submission and server response.

  6. Repeat token extraction and submission as required.

    Automate these steps for multiple protected endpoints.

Discuss the article:

Comment anonymously. Login not required.