CSRF: Generate token for every request

Right now, we have csrf token per session. And adding this token jsp's using hidden field. following snippet gives only one per session:

token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_NAME);
    if (null==token) {
        token = UUID.randomUUID().toString();
        session.setAttribute(CSRF_TOKEN_FOR_SESSION_NAME, token);

and for every request,

//calls the above snippet and this time token will not be null 
String st = CSRFTokenManager.getTokenForSession(request.getSession());
String rt = CSRFTokenManager.getTokenFromRequest(request);

here, usings equals to compare the strings and returning either true or false.

my question is, what happens if I try to generate the token for every request without getting the token from session. And while comparing, I will get from the session and request. is this good idea or missing something?

Instead of using the above snippets, I will go with following

    //for every request generate a new and set in session
    token = UUID.randomUUID().toString();
    session.setAttribute(CSRF_TOKEN_FOR_SESSION_NAME, token);

    //get the token from session and request and compare
    String st = (String) request.getSession().getAttribute("CSRF_TOKEN_FOR_SESSION_NAME");
    String rt = CSRFTokenManager.getTokenFromRequest(request);


You'll want to flip around the flow that you stated above. After every compare you should create a new token.

One large drawback to token-per-request is if the user hits the back button in their browser:

  • User visits Page1 and stores TokenA in session.
  • User clicks a link to Page2, submitting TokenA. The app verifies TokenA in session and gives the user TokenB.
  • User hits the back button to go back to Page1, session information is not updated.
  • Page1 still only has information for TokenA, user clicks a link or submits a form to Page3 submitting TokenA, but the session only knows about TokenB
  • App considers this a CSRF attack

Because of this, you need to take great care of how and when the tokens are updated.

Need Your Help

Android: Start Async Task in OnReceive Method

android android-asynctask broadcastreceiver

I currently have a Service which manages a Broadcast Receiver. This receiver can be turned off and on.

Component Paint method not painting to middle of JPanel?

java graphics resize drawing paint

Alright, so I have a JPanel with the paint method below, and it works just fine at first, but when the JPanel is resized(is in JFrame) is doesn't paint it to the center of the Frame.

Create image from BLOB using ImageIO?

java image blob

I tried to create image from BLOB. I try following code but it is not working at step: