java - 错误 HTTP 状态 403 - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN'

标签 java spring spring-mvc spring-security

嗨,我是 Spring security 的新手,我正在使用提到的示例 here 作者: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();

关于java - 错误 HTTP 状态 403 - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786757/

相关文章:

java - 优先级队列没有根据Java中的优先级返回正确的值

mysql - 如何在 Flyway 测试扩展中强制使用方言?

java - 在 @PostConstruct 中调用另一个 bean 的方法引发了一个空指针 ex

Spring MVC 表单不采用对象路径

java - org.springframework.beans.factory.BeanCreationException : in Ecommerce project

java - JAXB如何生成可能带有嵌套元素的元素?

java - 推荐人

java - 比较法违反了它的一般契约。简单比较

java - Spring MVC : Generic DAO and Service classes

java - 测试 Spring MVC 注释映射