I want to download files from my angularJS client. I have enabled CSRF protection and works fine, except when I try to upload a file where I get an error 403:
An invalid CSRF token "null" was found in the request parameter "_csrf" or the header "X-XSRF-TOKEN".
But the token is in the request headers and is correct! When I turn off CSRF protection, I can upload files without problems.
In addition, CSRF protection works great.
Here is my current configuration:
SecurityConfiguration.java
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityUserDetailsService securityUserDetailsService;
@Autowired
private AuthFailureHandler authFailureHandler;
@Autowired
private AjaxAuthSuccessHandler ajaxAuthSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authFailureHandler)
.and()
.authorizeRequests()
.antMatchers(
"/",
"/index.html",
"/styles/**",
"/bower_components/**",
"/scripts/**"
).permitAll().anyRequest()
.authenticated()
.and().formLogin().loginPage("/login").permitAll()
.and().logout().logoutUrl("/logout").logoutSuccessHandler(ajaxAuthSuccessHandler).permitAll()
.and().httpBasic()
.and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.csrf().csrfTokenRepository(csrfTokenRepository());
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(securityUserDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
CsrfHeaderFilter.java
public class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
And the last thing I added is SecurityWebApplicationInitializer, as indicated here .
SecurityWebApplicationInitializer.java
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
?
: , 403.
@Configuration
public class MultipartUploadConfig {
@Bean(name = "filterMultipartResolver")
public MultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}