title: How to prevent my web app from CSRF(Cross site request forgery) in java
body: <p>I am trying to prevent my web application from CSRF(Cross site request forgery)
  I followed this link <a href="https://dzone.com/articles/preventing-csrf-java-web-apps" rel="noreferrer">Link for CSRF</a></p>
  
  <p>This is what I have tried.
  To implement this mechanism in Java I choose to use two filters, one to create the salt for each request, and another to validate it. Since the users request and subsequent POST or GETs that should be validated do not necessarily get executed in order, I decided to use a time based cache to store a list of valid salt strings.</p>
  
  <p>The first filter, used to generate a new salt for a request and store it in the cache can be coded as follows:</p>
  
  <pre><code>public class LoadSalt implements Filter{
  
  
      public void doFilter(ServletRequest request, ServletResponse response,
              FilterChain chain) throws IOException, ServletException {
  
          // Assume its HTTP  
          HttpServletRequest httpReq = (HttpServletRequest)request;
          // Check the user session for the salt cache, if none is present we create one
          @SuppressWarnings("unchecked")
          Cache&lt;String, Boolean&gt; csrfPreventionSaltCache = (Cache&lt;String, Boolean&gt;)
                  httpReq.getSession().getAttribute("csrfPreventionSaltCache");
  
          System.out.println("Checking cahce befor creating it from Request :csrfPreventionSaltCache: "+csrfPreventionSaltCache);
  
          if(csrfPreventionSaltCache == null)
          {
              System.out.println("csrfPreventionSaltCache is null have to create new one");
              String csrfPreventionfromrequest = (String) httpReq.getSession().getAttribute("csrfPreventionSaltCache");
              System.out.println("csrfPreventionfromrequest :"+csrfPreventionfromrequest);
  
              // creating a new cache 
              csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(5000)
                      .expireAfterAccess(20, TimeUnit.MINUTES).build();
  
              // Setting to gttpReq
              httpReq.getSession().setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache);
  
              System.out.println("After setting the csrfPreventionSaltCache to HttpReq");
              System.out.println("--------csrfPreventionSaltCache------ :"+httpReq.getSession().getAttribute("csrfPreventionSaltCache"));
          }
  
  
  
          // Generate the salt and store it in the users cache
          String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
          System.out.println("Salt: "+salt);
          csrfPreventionSaltCache.put(salt, Boolean.TRUE);
          // Add the salt to the current request so it can be used
          // by the page rendered in this request
          httpReq.setAttribute("csrfPreventionSalt", salt);
  
          System.out.println("Before going to validate salt checking for salt in request");
          System.out.println(" httpReq.getAttribute(csrfPreventionSalt) ----:"+httpReq.getAttribute("csrfPreventionSalt"));
         // System.out.println(" httpReq.getSession().getAttribute(csrfPreventionSalt) :----"+httpReq.getSession().getAttribute("csrfPreventionSalt"));
  
  
          chain.doFilter(request, response);
      }
      public void init(FilterConfig arg0) throws ServletException {
  
      }
  
      public void destroy() {
  
      }
  }
  </code></pre>
  
  <p><strong>Mapping in web.xml</strong></p>
  
  <pre><code>        &lt;filter&gt;
              &lt;filter-name&gt;loadSalt&lt;/filter-name&gt;
              &lt;filter-class&gt;com.globalss.dnb.monitor.security.LoadSalt&lt;/filter-class&gt;
          &lt;/filter&gt;
  
          &lt;filter-mapping&gt;
               &lt;filter-name&gt;loadSalt&lt;/filter-name&gt;
               &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
          &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>to validate the salt before executing secure transactions I have written another filter:</p>
  
  <pre><code>public class ValidateSalt implements Filter {
  
      public void doFilter(ServletRequest request, ServletResponse response,
              FilterChain chain) throws IOException, ServletException {
  
          // Assume its HTTP
          HttpServletRequest httpReq = (HttpServletRequest) request;
  
          //String salt = (String) httpReq.getSession().getAttribute("csrfPreventionSalt");
          String salt =(String) httpReq.getAttribute("csrfPreventionSalt");
          System.out.println("I am in ValidateSalt : salt: "+salt);
  
       // Validate that the salt is in the cache
          @SuppressWarnings("unchecked")
          Cache&lt;String, Boolean&gt; csrfPreventionSaltCache = (Cache&lt;String, Boolean&gt;)
              httpReq.getSession().getAttribute("csrfPreventionSaltCache");
  
  
          if(csrfPreventionSaltCache !=null &amp;&amp; salt !=null &amp;&amp; csrfPreventionSaltCache.getIfPresent(salt)!=null)
          {
              // If the salt is in the cache, we move on
              chain.doFilter(request, response);
          }
          else
          {
              // Otherwise we throw an exception aborting the request flow
              throw new ServletException("Potential CSRF detected!! Inform a scary sysadmin ASAP.");
          }
  
      }
  
      public void init(FilterConfig arg0) throws ServletException {
  
      }
      public void destroy() {
  
      }
  
  }
  </code></pre>
  
  <p><strong>Mapping for the second Filetr in web.xml</strong></p>
  
  <pre><code>&lt;filter&gt;
              &lt;filter-name&gt;validateSalt&lt;/filter-name&gt;
               &lt;filter-class&gt;com.globalss.dnb.monitor.security.ValidateSalt&lt;/filter-class&gt;
          &lt;/filter&gt;
  
          &lt;filter-mapping&gt;
              &lt;filter-name&gt;validateSalt&lt;/filter-name&gt;
              &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
          &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>After configuring both servlets all your secured requests wasfailing :). To fix it you I had to add, to each link and form post that ends in a secure URL, the csrfPreventionSalt parameter containing the value of the request parameter with the same name. For example, in an HTML form within a JSP page:</p>
  
  <pre><code>&lt;form action="/transferMoneyServlet" method="get"&gt;
      &lt;input type="hidden" name="csrfPreventionSalt" value="&lt;c:out value='${csrfPreventionSalt}'/&gt;"/&gt;
      ...
  &lt;/form&gt;
  </code></pre>
  
  <p>After doing all this I try to attempt CSRF, This what I did</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
  &lt;body&gt;
  &lt;form action="http://localhost:8080/mywebapp/dispatcherServlet/addUserController/addUser" method="POST" enctype="text/plain"&gt;
  &lt;input type="hidden" name="&amp;#123;&amp;quot;userName&amp;quot;&amp;#58;&amp;quot;CSRUser&amp;quot;&amp;#44;&amp;quot;password&amp;quot;&amp;#58;&amp;quot;CSRFUser123&amp;quot;&amp;#44;&amp;quot;roles&amp;quot;&amp;#58;&amp;quot;true&amp;quot;&amp;#44;&amp;quot;status&amp;quot;&amp;#58;&amp;quot;true&amp;quot;&amp;#125;" value="" /&gt;
  &lt;input type="submit" value="Submit request" /&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>When I hit the submit request button , I got a success response,
  and CSRUser was added in my database.</p>
  
  <p>am I missing something, how do I prevent CSRF attack?</p>