Loading...
Loading...

Reputation: 169

How to validate CSRF tokens?

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

Answers (1)

RB_
RB_

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:

enter image description here

In more details it looks like this:

    1. User sends GET request to a server
    1. Server sets the cookie with sessionid, and saving session data with the token
    1. server returns HTML with a form containing token in a hidden field.
    1. User submits form, along with a hidden field
    1. server compares token from the submitted form (hidden field) with the token saved in the session storage. If they match, it means that form is submitted by a user.

Here is another great answer: Why is it common to put CSRF prevention tokens in cookies?

Upvotes: 11

Related Questions