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:

  1. 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)
  2. 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)
  3. 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)
  4. 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.

  • seems a little complicated; don't over-think it, CSRF techniques are pretty basic and well-documented
    – dandavis
    Jun 13, 2017 at 14:34

1 Answer 1


"csrfToken.js" which contains the token (var csrkToken="example")

This can also be read from other sites, like this:

<script src="http://yoursite.com/csrfToken.js"></script>

The same-origin policy does not protect against this.

This is possible because the file is a piece of JavaScript that assigns to a variable, and this can be read with a script tag. In contrast, if the file is a text file or JSON, it can't be read cross-origin

{"csrfToken": "example"}

You would read it yourself using an ajax request, but other sites can't do this.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .