Reputation: 6505
I am trying to secure my React/Express app using CSRF tokens.
I was following the first approach from this article but I don’t see how this is secure.
It suggests setting a CSRF token in the header for the first request (I’d assume when fetching the html, css and js for the page) and afterwards, return a new CSRF token with every call to the server.
My question is: Why can’t an attacker just fetch the site and also get access to the CSRF token?
My apologies if this is a duplicate, but whatever approach I seem to try, this question never truly gets demystified for me.
Upvotes: 1
Views: 5732
Reputation: 23
You can set the CSRF token in cookies when session starts. Cookies can be accessed by javascript. And set the time limit to cookies so that it will be automatically deleted after some time (eg.. 1hr)
Upvotes: 0
Reputation: 2197
I think the article you linked has the answer towards the end:
CSRF tokens are typically bound to the user's session, so your CSRF tokens won't work for me.
If an attacker sends a request to your server, they'll get a token for their own session. What they have to do to exploit another user is to trick that user into sending a request (maybe emailing them a suspicious link), so that their browser automatically sends their cookies to the server, since that's how browsers normally handle cookies.
The CSRF token adds an extra bit of required data that is NOT transmitted automatically. You have to send the token to the server in the 'X-CSRF-TOKEN' header, which is not transmitted automatically, unlike the normal 'cookie' request header which your browser sends automatically. This helps to prove that the request was a deliberate, legitimate request from a user, and not an accidental/malicious request that takes advantage of their current session.
Upvotes: 3