Spring Rest Service - Invalid CSRF token while trying to login

I have a Spring MVC REST service with Spring Security enabled (3.2.5.RELEASE). When I enable @EnableWebMvcSecurity, a login form is automatically created for me at http: // localhost: 8080 / login . If I use this form to login, everything works fine.

The problem occurs when I try to log in by sending a POST request directly. In my mail request, I specify the username and password. I also include the http "X-CSRF-TOKEN" header, and for the header value, I use the JSESSIONID, which, as I see it, was generated in the cookie. But when I send this POST request, I return the following result:

HTTP Status 403 - Invalid CSRF Token '29F5E49EFE8D758D4903C0491D56433E' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'. 

What am I doing wrong? Am I providing the wrong token value? What is this JSESSIONID? If I do not enter a value for this header or omit the header together, it tells me "CSRF Token Found."

The following is my Spring security configuration:

 @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/secure/**").authenticated() .and() .formLogin() .usernameParameter("username") .passwordParameter("password") .and() .logout() .and() .httpBasic() .and() .csrf(); } } 

I would really appreciate any help! Thanks in advance!

+6
source share
3 answers

You need to send the csrf token when submitting the login form. Add the following line to your HTML form:

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

(1) Include the CSRF token in all of 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 inquiry.

 <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> 
+4
source

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 use thimeleaf <meta name="_csrf" th:content="${_csrf.token}" />

0
source

Source: https://habr.com/ru/post/983010/


All Articles