ajaxsecuritycsrfcsrf-protection

How to protect against CSRF on a static site?


I have a static website, being served from a CDN, that communicates with an API via AJAX. How do I protect against CSRF?

Since I do not have control over how the static website is served, I cannot generate a CSRF token when someone loads my static website (and insert the token into forms or send it with my AJAX requests). I could create a GET endpoint to retrieve the token, but it seems like an attacker could simply access that endpoint and use the token it provides?

Is there an effective way to prevent against CSRF with this stack?


Additional details: authentication is completely separate here. Some of the API requests for which I want CSRF protection are authenticated endpoints, and some are public POST requests (but I want to confirm that they are coming from my site, not someone else's)


Solution

  • I could create a GET endpoint to retrieve the token, but it seems like an attacker could simply access that endpoint and use the token it provides?

    Correct. But CSRF tokens are not meant to be secret. They only exist to confirm an action is performed in the order expected by one user (e.g. a form POST only follows a GET request for the form). Even on a dynamic website an attacker could submit their own GET request to a page and parse out the CSRF token embedded in a form.

    From OWASP:

    CSRF is an attack that tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf.

    It's perfectly valid to make an initial GET request on page load to get a fresh token and then submit it with the request performing an action.

    If you want to confirm the identity of the person making the request you'll need authentication, which is a separate concern from CSRF.