Can't create CSRF token with Spring Security

前端 未结 6 1344
清酒与你
清酒与你 2020-12-29 10:26

I am using Spring Security 3.2.3 in my Spring MVC application and getting some unexpected behavior.

According to the documentation here, it should be possible to us

6条回答
  •  独厮守ぢ
    2020-12-29 10:59

    Before adding the thymeleaf-extras-springsecurity namespace and its dependency into my project, I had similar problems. I never did get the meta tags to work, even with thymeleaf-extras-springsecurity. But I did successfully retrieve Spring Security's csrf token using the hidden input. I have instructions below that work for me:
    In the html tag, add:
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

    In your pom.xml (if you're using Maven) you'll need to add the dependency: thymeleaf-extras-springsecurity4.
    Then add the hidden input inside your page's body to retrieve the csrf token.

    and then use that within your javascript/jquery as follows:
    function f1() { var token1 = $('input#csrf-token').attr("content"); ... $.ajax({ ... type: "POST", beforeSend: function (request) { request.setRequestHeader("X-CSRF-TOKEN", token1); }, ...
    This all assumes that you have spring security enabled, and that you have NOT turned off csrf protection.

提交回复
热议问题