Подтвердить что ты не робот

Spring Безопасность "Отказано от выполнения script из..."

Я создаю приложение Spring MVC с Spring Security и Bootstrap в моих HTML файлах (шаблоны тимелеафа). Защитная часть Spring основана на Spring Guide для Spring Безопасность и в сочетании с сервером приложений Spring.

После включения Spring Безопасность загрузочный файл css не загружается с сообщением об ошибке:

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. 

Сообщение об ошибке, приведенное выше, происходит от консоли разработчика Chrome.

Что я пробовал:

  • Отключение защиты Spring = > bootstrap css работает снова, но мне нужна безопасность
  • Поиск на форумах Spring, но theres looped link без решения
  • Добавление обработчика ресурсов, но я не вижу, что обработчик вызывается, и ошибка не исчезает.
  • Добавление пути ресурсов к вызову permit

Моя структура:

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

BootStart.java - это java файл, который загружается с помощью 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>

В настоящее время я использую следующие зависимости в моем 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>

Как мне настроить Spring Security, чтобы я мог загружать файлы css/js из каталога my/static resources?

4b9b3361

Ответ 1

Пожалуйста, проверьте этот ответ другим с похожим вопросом.

Если вы поместите js файлы в каталог /js/ dir, не должно быть такого MIME-ошибки.
И, для файлов javascript, лучше отключить их безопасность:

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

Ответ 2

У меня была такая же ошибка с той же структурой папок, что и в файле css.

Все, что я сделал, добавлено /css/** в antMatcher(), как показано ниже:

@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();

}

В вашем случае просто добавьте /js/** в antMatcher(), а затем используйте allowAll()

Ответ 3

У меня была такая же ошибка после добавления нового метода в контроллер.

Я забыл указать значение для аннотации @GetMapping, а сам @Controller не привязан к какому-либо URL-адресу. Довольно странно добавив @GetMapping("/foo") к моему методу, решила проблему. Я до сих пор не понял, почему это произошло, но я собираюсь это выяснить.

Ответ 5

Я использовал это, чтобы решить мою проблему, вы можете попробовать это

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

Надеюсь, это поможет.

Ответ 6

когда мы используем " allowall() " или anyrequest(), тогда включается проверка Mime, поэтому я указываю все списки URL, которые используются для принятия.