如何在spring-form JSP Tag Library中发送/包含CSRF Token

时间:2016-05-12 10:57:38

标签: java spring forms jsp spring-mvc

我的配置中启用了csrf()以下代码段的Spring表单:

<form:form action="save" method="post" modelAttribute="book" 
enctype="multipart/form-data">

  --

  <input type="submit" value="Save">
</form:form>

当我提交时,我收到错误Invalid CSRF token found

我已经在下面尝试了一些自定义:

  1. 添加令牌action="save?${_csrf.parameterName}=${_csrf.token}"以形成动作属性,但我的ModelAttibutes在我的控制器中返回NULL。
  2. 使用删除enctype="multipart/form-data"属性,令牌无效求解和模型属性具有适当的值,除了我的byte []字段,我也得到错误...is not a multipart request
  3. Web MVC Config Snippet:

    @Configuration
    @EnableWebMvc
    @EnableWebSecurity
    @ComponentScan("me.ariphidayat.lib")
    public class WebAppConfig extends WebMvcConfigurerAdapter {
    
      @Bean
      public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
      }
    
      ...
    
      @Bean
      public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        return resolver;
      }
    }
    

    网络安全配置代码段

    @Configuration
    @EnableWebSecurity
    @ComponentScan(basePackageClasses =
       me.ariphidayat.lib.service.impl.UserServiceImpl.class)
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
      ....
    
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/")
                    .permitAll()
                .and().logout()
                    .permitAll()
                .and().csrf()
                .and().rememberMe()
                    .tokenRepository(persistentTokenRepository())
                    .tokenValiditySeconds(60 * 60 * 24 * 7)
                .and().exceptionHandling()
                    .accessDeniedHandler(accessDeniedExceptionHandler);
      }
    }
    

    P.S。 :以前,我在配置中使用禁用csrf()对此进行了测试,没有任何问题。

0 个答案:

没有答案