Nov 10, 2021 3:02:42 PM Thomas Dumont avatar

Forms protection against CSRFs (cross-site request forgery)

To protect itself from cross-site request forgery (CSRF) injections, it is proposed to create and send with each form a random value limited to the action and user session. The server must check that this value is returned in the form validation request. For that it is necessary :

  • Add the token in the model object for the template:
model.put (SecurityTokenService.MARK_TOKEN, SecurityTokenService.getInstance().getToken(request, ACTION_TEMPLATE));
  • Add the token field in the template form:
<input type="hidden" name="token" value = "${token}">
  • Then check the request:
// CSRF Token control
         if (! SecurityTokenService.getInstance().validate(request, ACTION_TEMPLATE))
         {
             throw new AccessDeniedException ("Invalid security token");
         }