Search code examples
javaspring-mvcspring-securitycsrfcsrf-protection

CSRF (Cross-site request forgery) protection in spring MVC


I'm little confuse in this CSRF (Cross-site request forgery) protection in spring. No I have my jsp and my controller and a web service. What I want to do is validate the token at the web service level and if token is a match, run the web service (In my case do a db insert)

JSP file

    <form:input type="text" class="form-control" path="mName" />

    <input type="hidden" name="${_csrf.parameterName}"
        value="${_csrf.token}" />

    <div class="form-action">
        <input type="submit" value="Save" class="btn btn-primary" />
    </div>
</form:form>

I've inserted the hidden tag also. Now what should I do to validate this token. I'm little lost there.

At the controller class I get the values from the form to an object and call the web ervise to save data

@RequestMapping(method = RequestMethod.POST)
  public String processForm(@ModelAttribute(value = "userForm") @Valid UserForm userForm, BindingResult result, ModelMap model) {      

   //call the web service
  }

Solution

  • Apparently I was using spring security 3.1.4.RELEASE. here you have do this manually. Then I changed it to 3.2.2.RELEASE and then I just had to use

    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    

    Refer this link to see whats new in spring security 3.2

    http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#new

    Be careful, when you change from 3.1.4.RELEASE to 3.2.2.RELEASE, there are lot of confusing re factorings to do. Specially in web.xml and spring-security.xml files