24

I'm building a Spring MVC application with Spring Security and Bootstrap in my HTML files (thymeleaf templates). The Spring Security part is based on the Spring Guide for Spring Security and combined with a Spring Boot application server.

After enabling Spring Security the bootstrap css file won't load with the error message:

Refused to execute script from 'http://localhost:8080/js/bootstrap.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. 

The error message above comes from the chrome developer console.

What I've tried:

  • Disabling the Spring Security => bootstrap css works again, but I need the security
  • Searching on the spring forums, but theres a looped link without a solution
  • Adding a resources handler, but I can't see that the handler is invoked nor the error disappears
  • Adding the resources path to the permit call

My dir structure:

/main
  |-> /java
       | BootStart.java
       |-> /security
              |SecurityConfiguration.java
  |-> /resources
         |-> /static
               |-> /css /** bootstrap location */
               |-> /js
               |-> /fonts
         |-> /templates
               | /user
                   | sample.html

BootStart.java is the java file that gets picked up by Spring Boot.

BootStart.java:

@EnableAutoConfiguration
@ComponentScan
public class BootStart {
    public static void main(String[] args) {
        SpringApplication.run(BootStart.class, args);
    }
}

SecurityConfiguration.java:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
        http
                .authorizeRequests()
                .antMatchers("/", "/resources/static/**").permitAll()
                .anyRequest().authenticated();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

Sample.html:

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}" href="../../css/bootstrap.min.css"/>
    <link rel="stylesheet" th:href="@{/css/bootstrap-theme.css}" href="../../css/bootstrap-theme.min.css"/>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div class="alert alert-danger" role="alert">!Basic template!</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>

</body>
</html>

Currently I'm using the following dependencies in my pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>3.2.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>3.2.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.2.4.RELEASE</version>
</dependency>

How must I configure Spring Security that I can load css/ js files from my /static resources directory?

somenone
  • 241
  • 1
  • 2
  • 4

8 Answers8

21

Please check this answer by other with similar question.

If you place js files in /js/ dir, there should not that kind of MIME error.
And, for javascript files, it is better to disable security for them:

@Override
public void configure(WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/the_js_path/**");
}
Community
  • 1
  • 1
Mavlarn
  • 3,807
  • 2
  • 37
  • 57
14

I had the same error too with the same folder structure, it was on the css file.

All I did is added /css/** in antMatcher() as below:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

    httpSecurity
        .authorizeRequests()
            .antMatchers("/css/**").permitAll() //Adding this line solved it
            .anyRequest().fullyAuthenticated()
            .and()
        .formLogin()
            .loginPage("/login").permitAll()
            .loginProcessingUrl("/sign-in")
            .defaultSuccessUrl("/home")
            .failureUrl("/error")
            .and()
        .logout()
            .logoutSuccessUrl("/logout")
            .permitAll()
            .and()
        .csrf().disable();

}

In your case just add /js/** in the antMatcher() and then use permitAll()

da-vinci-code
  • 359
  • 4
  • 11
3

I used this to resolved my problem, you may try this

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
}

Hope it help.

Wei Chun
  • 1,263
  • 2
  • 10
  • 19
2

I had this problem, and struggled for a while. I had created a route which should match every "unmatched" route, and send index.html.

@Controller
public class DefaultPageController {
  @Autowired
  private LogService logService;

  @GetMapping("/*")
  public String defaultPage(Model model){
      logService.saveLog(Log.LogType.INFO, null, "Default route");
      return "index";
  }
}

The problem was, that it overrode the route /file.js, and didn't send the static files, but always index.html.

So the solution was only to customize the route.

Slawomir Wozniak
  • 489
  • 6
  • 14
0

I had the same error after adding a new method to a controller.

I forgot to provide a value for the @GetMapping annotation and the @Controller itself was not bound to any URL. Wierdly enough adding @GetMapping("/foo") to my method solved the problem. I still haven't figured out why that happened but I'm planning to find out.

Peter Catalin
  • 1,342
  • 1
  • 14
  • 22
0

when we use "permitall()" or anyrequest() then it enable Mime check so i specify all url listing which use to be accecs.

0

I removed any comments from the beginning of the css file and it works.

nllsdfx
  • 900
  • 14
  • 30
0

Checklists to import static resources file into Spring MVC with Security Web Configuration:

  1. Permit pattern matcher in configure method which extends from WebSecurityConfigurerAdapter
    @Override
        protected void configure(HttpSecurity http) throws Exception {
            
            http
                .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/loginPage").loginProcessingUrl("/authenticateUser")
                .permitAll();
        }
  1. Mapping resources location in configuration by implements WebMvcConfigurer
@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
  1. Create the resources folder and subfolders to store the static files.
/src/main/webapp/
    |-> resources
      | -> css
        | -> style.css
  1. Add resources into the JSP file
 <link rel="stylesheet" type="text/css" href="css/style.css">
  1. Remember that in the controller file always specify the path even though the home page @RequestMapping("/")
Pines Tran
  • 601
  • 4
  • 6