Skip to content

what if token expires

minhaz edited this page Oct 11, 2016 · 1 revision

Token expiry & work around

This issue was discussed in the thread https://github.com/mebjas/CSRF-Protector-PHP/issues/5 to a good depth. And several options were presented.

Issue: CSRF Protector employs cookie for transferring the secret token from server to client and takes advantage of the same origin policy of cookies to ensure it wont be misused. But cookies have an expiry time, and question is what happens if the token expires. Currently the expiry time is 30 minutes (https://github.com/mebjas/CSRF-Protector-PHP/blob/master/libs/csrf/csrfprotector.php#L326). This value was decided, so that library is generic to all.

NOTE: If the request is made after token expires, request will fail with a 403 or as configured

Here a few workarounds:

  1. Set fairly larger expiry period at https://github.com/mebjas/CSRF-Protector-PHP/blob/master/libs/csrf/csrfprotector.php#L32
  2. This method is trickier & involves modification of JS code. The idea is if you have expiry time set as t seconds, your script should set a timer for t - dt seconds for refreshing token. This can be a simple GET Request (ajax) with sole purpose of refreshing token in cookie. But this means you need to transfer expiry period information to JavaScript code as well, cookie can be used for this as well :p. Now if your application involves, multiple tabs an optimization would be to store last refresh time-stamp globally in cookie as well, so that multiple tabs doesn't issue the same call if not needed. This also means that your application has a specific endpoint just to deal with refreshing expiry tokens, which shouldn't be a big pain though.

Note: this document is in progress. feel free to suggest more points / edit may be.