Spring Rest Service - Invalid CSRF token when I attempt to login

后端 未结 3 913
Happy的楠姐
Happy的楠姐 2021-01-05 10:31

I have a Spring MVC REST service, with Spring Security (3.2.5.RELEASE) enabled. When I turn on @EnableWebMvcSecurity, a login form is automatically generated for me at http:

相关标签:
3条回答
  • 2021-01-05 11:08

    You need to send the csrf token when you submit the login form. Please add the below line in the HTML form:

    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    
    0 讨论(0)
  • 2021-01-05 11:23

    you need <meta name="_csrf" content="${_csrf.token}"/> , https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/#ajax-requests

    or if you are using thymeleaf <meta name="_csrf" th:content="${_csrf.token}" />

    0 讨论(0)
  • 2021-01-05 11:32

    (1) Include the CSRF token within all your AJAX requests.

    $(function () {
        var token = $('#logoutform>input').val();
        var header = $('#logoutform>input').attr('name');
        $(document).ajaxSend(function(e, xhr, options) {
            xhr.setRequestHeader('X-CSRF-TOKEN', token);
        });
     });
    

    (2) Simple request .

    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    
    0 讨论(0)
提交回复
热议问题