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.
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:
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:
Content-Type: application/json
request header).… or both.