Spring Security - All JQuery Ajax post requests return 404

后端 未结 4 998
说谎
说谎 2021-02-05 23:14

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

4条回答
  •  鱼传尺愫
    2021-02-06 00:09

    Alternative solution using Spring Boot 2.2.1 with Spring MVC, Spring Security 5 and Thymeleaf 3.0.11

    I am so happy that I finally found a solution to this problem, that I would also like to share it here:

    Problem:

    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).

    Solution:

    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";
        }
    

提交回复
热议问题