Spring Rest Service - 尝试登录时无效的CSRF令牌

Ale*_*exG 7 rest spring spring-mvc spring-security http-authentication

我有一个Spring MVC REST服务,启用了Spring Security(3.2.5.RELEASE).当我打开@EnableWebMvcSecurity时,会在http:// localhost:8080/login为我自动生成一个登录表单.如果我使用此表单登录,一切正常.

当我尝试通过直接发送POST请求登录时,会发生此问题.在我的帖子请求中,我提供了用户名和密码.我还包括http标头'X-CSRF-TOKEN',对于标头值,我使用我看到的JSESSIONID已在cookie中生成.但是,当我发送此POST请求时,我得到以下结果:

HTTP Status 403 - Invalid CSRF Token '29F5E49EFE8D758D4903C0491D56433E' 
was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我提供了错误的令牌价值吗?这是什么JSESSIONID?如果我没有为此标题输入值,或者一起省略标题,则会告诉我"找到空的CSRF标记".

以下是我的Spring Security配置:

@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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

我真的很感激任何帮助!提前致谢!

Par*_*nki 5

(1)在所有AJAX请求中包含CSRF令牌.

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

(2)简单的要求.

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
Run Code Online (Sandbox Code Playgroud)


Mit*_*hun 4

您需要csrf在提交登录表单时发送令牌。请在 HTML 表单中添加以下行:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Run Code Online (Sandbox Code Playgroud)