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