Bootstrap не работает при использовании Spring Security

Я сейчас вхожу в Spring Boot и работаю над небольшим примером проекта. Но я столкнулся с действительно запутанной проблемой из-за использования Bootstrap с пакетом Spring-Boot-Security. Когда я использую следующий код, страница не отображается с помощью Bootstrap.

Мой SecurityConfiguration.java выглядит так

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests().antMatchers("/","/products","/product/show/*","/console/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .and()
            .logout().permitAll();

        httpSecurity.csrf().disable();
        httpSecurity.headers().frameOptions().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("admin").password("{noop}admin").roles("ADMIN")
            .and().withUser("user").password("{noop}user").roles("USER");
    }
}

Что мне кажется немного запутанным, так это то, что я получаю 301/ Unmodified, но, пытаясь избежать проблем с кэшированием, я полностью открыл браузер и использовал личное окно.

Когда я отключаю почти все функции безопасности, моя страница корректно отображается с помощью Bootstrap.

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests().antMatchers("/","/products","/product/show/*","/console/**").permitAll();


        httpSecurity.csrf().disable();
        httpSecurity.headers().frameOptions().disable();
    }
}

Я включаю бутстрап используя Webjars

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.3.4</version>
</dependency>

В моем Frontend Code используется шаблонный движок под названием Thymeleaf, Я включаю загрузчик со следующим кодом:

 <link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/css/bootstrap.min.css"
          th:href="@{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
          rel="stylesheet" media="screen" />

Включенное выше находится внутри файла с именем headerinc.html, который включен в текущую страницу, как это:

<!DOCTYPE html>
<html>
<head lang="en">

    <title>Spring Framework Guru</title>

    <!--/*/ <th:block th:include="fragments/headerinc :: head"></th:block> /*/-->
</head>
<body>

<div class="container">
    <!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->
</div>
</body>
</html>

Что не может быть проблемой: Например, не используя mvn clean / mvn install. Я сделал это.

Может ли кто-нибудь указать мне правильное направление здесь? Заранее спасибо.

3 ответа

Решение

Используйте это для авторизации всех файлов ресурсов, доступных в папке src/main/resources/static, вы можете соответственно добавлять папки.

//this method allows static resources to be neglected by spring security
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**","/webjars/**");
    }

Для меня сработало решение ниже:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/css/**", "/js/**", "/webjars/**").permitAll()
               .anyRequest().authenticated(). ...;
    }

Я попытался переместить его в статическую папку, и это сработало для меня.

Другие вопросы по тегам