Search code examples
jsonrestapisecuritycsrf

Is it safe to use a custom required HTTP header as a protection method from the CSRF for an API?


I have a JSON API built for a SPA which accepts only requests with "Accept: application/json" header. So submitting the following form in the browser will cause "Not Acceptable." HTTP error.

<form method="POST" action="https://api.example.domain/resource">
    <input type="password" name="password" value="CSRF">
    <input type="submit" value="Click!">
</form>

Is it means that the API has an immune to CSRF types of attack or am I missing something?


Solution

  • It should be quite secure, but still, there's a chance that the API is vulnerable.

    If an attacker could find an XSS vulnerability in the website he could be able to add the header: Accept: application/json using JavaScript and then perform the CSRF attack.

    For that reason, the recommendable is to rely on some headers that can't be set by JavaScript because they are on the 'forbidden' headers list, only browsers can modify them so no XSS vulnerability can be used in here.

    You will find more information in OWASP: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet