Reputation: 169
I'm trying to use the Hapi's plugin Crumb to implement a solution againts CSRF attacks, but seems that I didn't get the solution flow. I could simply set a token in each http response as a cookie. And here comes the question, how REST can validate CSRF token, if token issued by client? How REST backend understand what this random string is valid for this request and another random string is not?
Upvotes: 1
Views: 14121
Reputation: 1192
It's not possible to generate CSRF token on the client. It should be sent from the server to the client first, some JS frameworks extract it automatically from the cookie and send it to the server.
The basic idea is that user is supposed to send token along with a cookie and also in the post data. Here is a simple example. If attacker will trick a user to send a particular request to a service, for instance malicious website can have an image with this link src="gmail.com/deleteaccount=true"
. If user is logged in to gmail. Gmail will think that it was a user who made the request, because cookie send along with request is valid. So, in order to make sure that it was actually a user, gmail also requires a token send with a request data: so instead of gmail.com/deleteaccount=true
it needs gmail.com/deleteaccount=true&token=987y23459827345sdfg.
Token have to match the one stored in the cookie. So when request is received by a server, it checks if token in the cookie equals to token in the request body. Attacker have no access to user's cookies and don't know the token.
Here is the simplified data flow:
In more details it looks like this:
Here is another great answer: Why is it common to put CSRF prevention tokens in cookies?
Upvotes: 11