Reputation: 2424
I'm developing a web API. authentication is through cookies. All endpoints receive parameters through JSON
in the request body.
Do I need to implement a CSRF token
to protect them?
How can this be exploitable? Is it possible to send JSON through a normal <form>
element?
Is it possible for an attacker to have something like this?
<form type="application/json" method="POST">
<input name="json" value="{ my json code here }">
<input type="submit">Send</input>
<form>
Upvotes: 12
Views: 3208
Reputation: 910
there's no attribute named type
for HTML forms. The closest attribute is enctype
, and you can find it's reference here. The only valid values for the attribute are:
-application/x-www-form-urlencoded
, the default. All characters are encoded before sent (spaces are converted to "+" symbols, and special characters are converted to ASCII HEX values)
-multipart/form-data
, No characters are encoded. This value is required when you are using forms that have a file upload control.
-text/plain
Spaces are converted to "+" symbols, but no special characters are encoded.
Therefore a simple form can not submit a valid JSON payload.
Upvotes: 2
Reputation: 39
CSRF Token is a must, maybe you can add some hash based on the value and match it later, and you might be want to consider using ajax to send the value rather than put it inside an input, since JSON often have double quotes lie value="{name:""}" and that will make the HTML become invalid.
Upvotes: 0
Reputation: 1668
Firstly, you have to secure your API to avoid HTML/JavaScript injections that can cause CSRF attacks on OTHER sites. To do it:
use HTTPS for all communications to avoid MITM attacks
sanitize all income data to prevent HTML/JavaScript/SQL/LDAP/Command/... injections. You can also use web application firewall or WAF that prevents different types of attacks.
Use HTTP headers:
X-XSS-Protection "1; mode=block" - this header enables the Cross-site scripting (XSS) filter built into most recent web browsers.
Content-Security-Policy - this header tells the browser that it can only communicate with the domains you explicitly allow.
In case your API provides any sensitive information than use CSRF token to avoid CSRF attacks on YOUR API. The CSRF attack to your API can be done for example by injected JavaScript to another website. In this case the injection can make correct AJAX request.
Upvotes: 2