Search code examples
javascripthtmlnode.jsexpresscsrf

How to prevent CSRF attacks?


I want to prevent CSRF attacks on my API (Express app nodejs) I searched google and youtube but I can't find way to do it. On the youtube tutorial it said generate a token and send it to the client side but won't the hacker just send a request to get csrf token and bypass the csrf thingy? I'm confused please help.


Solution

  • A traditional CSRF attack works by placing a pre-populated form on the the attacker's site and submitting it cross-origin. It then uses credentials that are automatically sent with the request to send the attacker's data under the guise of the browser owner's identity.

    By putting a token in both the cookies (or session) and the form and checking to see if they match, you can defend against this. The attacker can't just send a request to get the CSRF token because:

    • If they get the user to make the request then the Same Origin Policy prevents them from reading the response with the token in it
    • If they make the request directly then they won't have the user's cookies so will get a different (non-matching) token

    When you are dealing with a web service (and you need to make that API work across origins), things are different. The key defence here is to design the API so either:

    • The credentials go somewhere where they won't be sent automatically (e.g. in an Authorization header) so the attacker can't make the request with them.
    • The request is in a format where it requires a CORS preflight request to send (e.g. with a Content-Type: application/json request header).

    … or both.