Bootstrap не работает при использовании Spring Security - PullRequest
0 голосов
/ 04 декабря 2018

Я сейчас вхожу в 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");
    }
}

Dev-Console-Network

Что меня немного смущает, так это то, что я получаю 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>

В моем интерфейсеКод с использованием шаблона Engine называется 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.Я сделал это.

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

1 Ответ

0 голосов
/ 04 декабря 2018

Используйте это для авторизации всех файлов ресурсов, доступных в папке 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/**");
    }
...