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

2022-09-01 14:53:25

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

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>

登录页面:

<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错误页面:

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.

怎么了,我该如何解决这个问题?我在配置中进行了注释,但错误消息与.csrfcsrf


答案 1

我遇到了同样的问题。我使用百里香和Spring boot,当我尝试以表单形式发布数据时,得到了CSRF令牌问题。

这是我的工作解决方案:

  1. 添加此隐藏输入:

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

  2. 在 (扩展 ), 添加一个方法:WebSecurityConfigWebSecurityConfigurerAdapter

    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())
    

我花了很多时间在这个问题上。希望它可以帮助有同样问题的人。


答案 2

如果必须禁用它...

在Spring Security 4中,使用XML配置时,CSRF默认处于启用状态。以前,默认情况下,它仅对基于 Java 的配置启用。

根据Spring安全文档的第14.4.2节

从Spring Security 4.0开始,CSRF保护默认使用XML配置启用。如果要禁用 CSRF 保护,可以在下面看到相应的 XML 配置。

<http>
   ...
   <csrf disabled="true"/>
   ...
</http>

推荐