Search code examples
cssspring-securitymime-typestomcat9

css files are not loaded because strict MIME checking is enabled when using spring security5


Spring security 5 blocks my css files when content type option is "nosniff". spring security does not block extern css files from other sites or css files brought by frameworks like struts2, it does however block css files that I create even if the file is empty like this one:

<link type="text/css" rel="stylesheet" href="reclamation/css/style2.css"/> the error message is : Refused to apply style from {fileName} because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I validated the css file with no errors but still got the problem. here are the headers:

Request URL: http://localhost:8080/reclamation/reclamation/js/style2.css Referrer Policy: no-referrer-when-downgrade Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Language: en Content-Length: 1123 Content-Type: text/html;charset=utf-8 Date: Tue, 21 Jul 2020 10:45:08 GMT Expires: 0 Pragma: no-cache X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Accept: text/css,/;q=0.1 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,fr;q=0.8,ar;q=0.7 Cache-Control: no-cache Connection: keep-alive Cookie: JSESSIONID=EA9A3D0AC31CDB51C68E0806CD5C32E1 DNT: 1 Host: localhost:8080 Pragma: no-cache Referer: http://localhost:8080/reclamation/list-complaint.action Sec-Fetch-Dest: style Sec-Fetch-Mode: no-cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Mobile Safari/537.36

permitAll is not a solution because it permits access but keeps security filters

<http pattern="/css/**" security="none"/> works but it deletes X-Content-Type-Options: nosniff for the css files. by the way security="none" solves the problem when working with eclipse but when I deploy the war directly in tomcat9 it is ignored and css files are not loaded.

my configuration: struts2, jdk8 tomcat 9.0.19 , spring security 5.1.6.RELEASE


Solution

  • I found the solution, I had filter who was changing all files to "text/html"

    public class CharacterSetFilter implements Filter {
     
    public void destroy() {}
    
    public void doFilter(
      ServletRequest request, 
      ServletResponse response, 
      FilterChain next) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");//this line was the problem
        response.setCharacterEncoding("UTF-8");
        next.doFilter(request, response);
    }
    
    // ...
    

    }