未找到预期的CSRF令牌。您的会话是否已过期403

问题描述:

我正在尝试使用mkyong示例编写我的测试Spring安全应用程序。

I'm trying to write my test spring security application with mkyong examples.

Spring Security: 4.0.0.RC1
Spring: 4.1.4.RELEASE

我有以下安全配置:

<http auto-config="true">
    <intercept-url pattern="/admin**" 
                    access="hasRole('ADMIN')"/>
    <form-login authentication-failure-url="/?auth_error" 
                        username-parameter="user" 
                        password-parameter="password" 
                        login-page="/"
                        default-target-url="/?OK"/>
<!-- <csrf/> -->
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="mkyong" password="123456" authorities="ADMIN" />
        </user-service>
    </authentication-provider>
</authentication-manager>

login-page:

login-page:

<html>
<body>
<form method="POST">
    <label for="user">User: </label>
    <input type="text" id="user" name="user" /> </br>
    <label for="password">Password: </label>
    <input type="text" name="password" id="password" /> </br>
    <input type="submit" /> 
</form>
</body>
</html>

现在,当我尝试登录时,我得到403错误页面:

Now, when I try to login I get 403 error page:

Invalid CSRF Token 'null' was found on the request parameter 
'_csrf' or header 'X-CSRF-TOKEN'.

描述:

Access to the specified resource (Invalid CSRF Token 'null' was
found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.) has been 
forbidden.

出了什么问题,我该如何解决?我在配置中评论了 csrf ,但错误消息与 csrf 有关。

What's wrong, how can I fix that? I commented csrf in the config, but the error-message has to do with the csrf.

我遇到了同样的问题。我使用thymeleaf和Spring启动,当我尝试在表单中发布数据时,我遇到了CSRF令牌问题。

I had the same problem. I use thymeleaf and Spring boot, and got the CSRF token issue when I try to post data in a form.

这是我的工作解决方案:

Here is my working solution:


  1. 添加此隐藏输入:

  1. Add this hidden input:

< input type = hiddenth:name =$ {_ csrf.parameterName}th:value =$ {_ csrf.token}/>

WebSecurityConfig (扩展 WebSecurityConfigurerAdapter )中,添加一个方法:

In your WebSecurityConfig (which extends WebSecurityConfigurerAdapter), add a method:

private CsrfTokenRepository csrfTokenRepository() 
{ 
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
    repository.setSessionAttributeName("_csrf");
    return repository; 
}

并在方法 configure()中添加代码

@Override
 protected void configure(HttpSecurity http) throws Exception {
     http.csrf()
     .csrfTokenRepository(csrfTokenRepository())


我花了很多时间来解决这个问题。希望它可以帮助那些遇到同样问题的人。

I spent lot of time on this problem. Hope it can help someone who has the same problem.