All my $.ajax
, both POST
and GET
were working fine, but as soon as I integrated Spring security 3.2.6
into my project the
I am so happy that I finally found a solution to this problem, that I would also like to share it here:
In my case, it was a $.ajax POST request to a valid URL returning 404 error status (not found).
@Mushtaq Jameel has explained that the original cause of the problem is csrf, which is enabled by default as of Spring Security 4 (source).
I have not tested what @Mushtaq Jameel proposed, but this elegant quick fix worked for me:
AJAX code:
$.ajax({
type: "POST",
url: "/",
data: $('.cd-signin-modal__form.sign-up').serialize(), // <- FIX
success: // some code
error: // some code
});
}
In other words, the solution is calling the .serialize() method on the HTML form itself.
What happens then, is that a _csfr token is automatically added in the POST request as an additional form parameter:
This is again due to csrf being enabled by default in the newer versions of Spring Security (here it is mentioned that this hidden form parameter is added automatically).
My Spring MVC controller then accepts the form like this:
@PostMapping("/")
public String createUser(@Valid @ModelAttribute User user, @Valid @ModelAttribute UserDetails userDetails, BindingResult errors) {
if (errors.hasErrors()) {
// handle errors
}
// persist objects in database
return "index";
}