Refreshing CSRF Tokens

cross-domaincsrfSecurity

I am trying to implement a user friendly anti CSRF mechanism.

  1. Currently my application program sets a cookie and session variable with the anti-csrf token and sends it to user.
  2. Whenever the user makes an unsafe request(POST,DELETE,PUT) javascript reads the cookie and adds the token to the form which is sent via an ajax request
  3. On server the form value is compared with session contained value.

Problem is my application will be open in multiple tabs and it it highly probable the the token will expire on server.

Is it a good practice to get new csrf tokens from a server file like
get-csrf-token.php
Because anyways the attacker cannot read the response from cross site requests(considering jsonp and cors is disabled)

EDIT:
I plan to keep single CSRF token valid per hour per session and the web applications will re-request new tokens after an hour

Is there anything wrong with this approach?

Best Answer

You only need one CSRF token per user session. As any attacker cannot read the token due to the Same Origin Policy, you do not need to refresh the token until the next session is active. This will mean there will be no problems with your application being open in multiple tabs.

Your approach is an implementation of the Synchronizer Token Pattern CSRF protection mechanism, which is the OWASP recommended approach. As JavaScript is used to add the value to the request, you can't mark your cookie as httpOnly. This would have prevented any XSS vulnerabilities from allowing an attacker to grab your cookie value. However, if you do have any XSS vulnerabilities, these are slightly more serious than CSRF ones and should be addressed immediately anyway as there are other attack vectors once an XSS flaw is found.

See this post for some pros and cons of some CSRF mechanisms: Why is it common to put CSRF prevention tokens in cookies?