错误 HTTP 状态 403 - 在请求参数'_csrf'或标头'X-CSRF-TOKEN'上发现无效的 CSRF 令牌'null'



嗨,我是 Spring 安全性的新手,我正在使用这里提到的例子 通过 Mkyong,我正在使用本教程中提供的基于注释的示例,但是每当我在登录表单中输入值并单击提交按钮时,它总是通过异常,如下所示。

type Status report
message Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
description Access to the specified resource has been forbidden.

我尝试谷歌它,但没有找到任何合适的答案,可以解决这个问题。 安全配置类如下。

安全配置.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("authenticationProvider")
    AuthenticationProvider authenticationProvider;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/admin/**")
            .access("hasRole('ROLE_USER')").and().formLogin()
            .loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username")
                .passwordParameter("password")
                .and().logout().logoutSuccessUrl("/login?logout").and().csrf();
    }
}

登录.jsp表格如下

<form name='loginForm'
            action="<c:url value='/login'/>" method='POST' enctype="multipart/form-data">
            <table>
                <tr>
                    <td>User:</td>
                    <td><input type='text' name='username'></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type='password' name='password' /></td>
                </tr>       
                <tr>                
                    <td colspan='2'><input name="submit" type="submit"
                        value="submit" /></td>
                </tr>
            </table>
<input type="hidden" name="${_csrf.parameterName}"
            value="${_csrf.token}" />
        </form>

请帮助我从这个问题中走出来。

请将以下代码添加到您的安全配置中,看看它是否会产生任何差异

.and()
          .csrf().disable();

问题在于多部分表单类型,您只需要使用它

<form name='loginForm'
            action="<c:url value='/login'/>" method='POST'>

而是你的原件下面

<form name='loginForm'
            action="<c:url value='/login'/>" method='POST' enctype="multipart/form-data">
如果您需要将表单

类型用作多部分表单,而不是将多部分过滤器添加到 Web.xml请确保在 Spring 安全性配置之前添加它:

<filter>
    <display-name>springMultipartFilter</display-name>
    <filter-name>springMultipartFilter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>springMultipartFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

最新更新