繁体   English   中英

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

[英]Error HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

嗨,我是Spring security的新手,我使用的是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.

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

SecurityConfig.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();
    }

}

login.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中添加MultipartFilter,以确保将其添加到Spring Security配置之前:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM