CharacterEncodingFilter don't work together with Spring Security 3.2.0

We need to add CharacterEncodingFilter before filters who read request properties for the first time. There is securityFilterChain (stands second. after metrica filter) and we can add our filter inside it. The first filter (inside security chain) who reads properties is CsrfFilter, so we place CharacterEncodingFilter before it.

The short solution is:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.addFilterBefore(filter,CsrfFilter.class);
        //rest of your code   
    }
//rest of your code
}

I ran into the same issue recently and your first try is actually very close to the solution I ended up using (here's your code, fixed) :

public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter());
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", "true");
    characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
    }
}

The only difference is the second argument when adding filter mapping for url patterns. The Javadoc for this parameter states :

isMatchAfter - true if the given filter mapping should be matched after any declared filter mappings, and false if it is supposed to be matched before any declared filter mappings of the ServletContext from which this FilterRegistration was obtained

So setting it to false should cleanly solve your issue (without any XML involved).


I don't know what exactly the problem is but I'd never configure such a simple filter inside Spring. Rather do it right in web.xml - easier to develop, understand and debug.

  <!-- Hint: http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

Important: configure this filter's mapping before the Spring Security filter chain (i.e. before the filter mapping for DelegatingFilterProxy).