api
CSRF

Documentation

Base URL

https://api.i-as.dev/api/csrf/

1. Get CSRF Token

  • Endpoint: /token
  • Method: GET
  • Description: Generates a new CSRF token.
Response:
{
  "token": "<csrf-token>"
}
Request:
GET /token
cURL:
curl -X GET /token

2. Send Data with CSRF Token

  • Endpoint: /secure
  • Method: POST
  • Description: Accepts data securely with CSRF protection.
Headers:
Content-Type: application/json
x-csrf-token: <csrf-token>
Request Body:
{
  "key": "value"
}
Response:
{
  "message": "Data received"
}
Request:
POST /secure
  Content-Type: application/json
  x-csrf-token: <csrf-token>
{
  "key": "value"
}
cURL:
curl -X POST /secure \
  -H "Content-Type: application/json" \
  -H "x-csrf-token: {csrf-token}" \
  -d '{"key": "value"}'

3. Error Responses

  • Expired Token:

    {
      "error": "Token expired"
    }
    
  • Invalid Token:

    {
      "error": "Invalid token"
    }
    

4. Example Usage

  • Fetching CSRF Token and Sending Data (JavaScript):
// Get CSRF token
async function getCsrfToken() {
  try {
    const response = await fetch('/token');
    const data = await response.json();
    return data.token;
  } catch (error) {
    console.error('Error fetching CSRF token:', error);
  }
}

// Send data with CSRF token
async function sendData() {
  const token = await getCsrfToken();
  if (token) {
    try {
      const response = await fetch('/secure', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': token
        },
        body: JSON.stringify({ key: 'value' })
      });
      const data = await response.json();
      console.log('Response:', data);
    } catch (error) {
      console.error('Error sending data:', error);
    }
  }
}

sendData();

Demo:

Download Demo