Spring Rest Service-尝试登录时无效的CSRF令牌 [英] Spring Rest Service - Invalid CSRF token when I attempt to login

查看:242
本文介绍了Spring Rest Service-尝试登录时无效的CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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://localhost:8080/login. If I use this form to login, everything works just fine.

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

The problem occurs when I attempt to login by sending a POST request directly. In my post request, I provide the username and password. I also include the http header 'X-CSRF-TOKEN' and for the header value, I use the JSESSIONID that I see has been generated in a cookie. But when I send this POST request, I get back the following result:

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

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

What am I doing wrong? Am I providing the wrong token value? What is this JSESSIONID? If I don't enter a value for this header, or omit the header all together, it tells me "Null CSRF token found".

以下是我的Spring Security配置:

Below 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'd really appreciate any help! Thanks in advance!

推荐答案

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

(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)简单请求.

(2) Simple request .

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

这篇关于Spring Rest Service-尝试登录时无效的CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆