I am using a java/scala app to write a web server (for learning purposes, so no frameworks allowed). I thought about the folowing way of implementing csrf tokens, but I am not sure if it is secure:
1 each html page includes the script "csrfToken.js" which contains the token (var csrkToken="example") 2 when this file is requested the csrf token gets loged into the server (along the userid to make the token only usable by that particular user). 3 when sending a post, put, delete etc the client reads the token from the js file and adds it to the request 4 when ever a post, put, delete, etc request reaches the server the token is checked 5 if the request is succesfull the token gets deleted and the site refreshed (to get a new token) 6 if not the site gets notified, the token does not get deleted and can be reused
Note: the tokens have a max lifespan (lets say 30 min). If the site remains open for longer (lets say multi tab browsing) the use gets notified that he should refresh the site before proceeding
The main problems here are:
- The token can be generated via get requests (this is a violation of how get requests should work, but shouldn't be a security concern because the same origin policy stops an attacker from reading the response to a cross site request)
- I am not sure wheteher or not an attacker could read the users csrf token in a mallicous site and then use it (asume my site is xss secure)
- I do not know if my csrf token having a short lifespan actually provides any aditional security or just decreases user expirience (consider the token is long enough for a brute force attack to be no concern)
- Edit: A csrf script could in generate lots of gets in order to create lots of csrf tokens for the same user. That is why i wish to cap the max number of csrf tokens a user can have at any given time (lets say 25 should be enough for any given user, but I'm not sire whether or not this number is appropiate)
If someone could tell me whether or not my implementation is secure and/or how to improve it I would greatly appreciate it.