2017-01-28 11 views
2

Я хотел добавить файл CSS в свой HTML-файл. Проблема возникла, когда я попытался добавить CSS в приложение Spring Security (я работаю над базовым содержимым Spring Getting Started Content). Я обвиняю Spring Security, потому что без него загружается файл CSS.Добавить файл CSS в Spring Boot + Spring Security Thymeleaf file

Application.java файл:

package mainpack; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class Application { 

    public static void main(String[] args) throws Throwable { 
     SpringApplication.run(Application.class, args); 
    } 
} 

MvcConfig.java файл:

package mainpack; 

import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 

@Configuration 
public class MvcConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
     registry.addViewController("/home").setViewName("home"); 
     registry.addViewController("/").setViewName("home"); 
     registry.addViewController("/hello").setViewName("hello"); 
     registry.addViewController("/login").setViewName("login"); 
     registry.addViewController("/index").setViewName("index"); 
     registry.addViewController("/register").setViewName("register"); 
     registry.addViewController("/whatever").setViewName("whatever"); 
    } 
} 

WebSecurityConfig.java файл:

package mainpack; 

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; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/", "/home", "/index", "/register", "../static/css", "../static/images").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
      .logout() 
       .permitAll(); 
    } 

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

загружаю CSS с линией:

<link href="../static/css/index.css" th:href="@{/css/index.css}" rel="stylesheet" /> 

в index.html файла.

ответ

2

Вашего шаблона ../static/css не соответствие вашего относительного URL ../static/css/index.css см AntPathMatcher:

реализации

PathMatcher для моделей пути Ant-стиль.

Часть этого кода сопоставления была любезно взята из Apache Ant.

отображение ссылок URL, используя следующие правила:

  • ? матчей одного персонажа
  • * соответствует нулю или более символов
  • ** соответствует нулю или больше каталогов в пути
  • {spring:[a-z]+} спичках regexp [a-z]+ в качестве переменной пути под названием «пружина»

и Spring Boot Reference:

По умолчанию ресурсы отображаются на /**, но вы можете настроить это через spring.mvc.static-path-pattern.

Ваш запрос будет перенаправлен на форму входа, потому что вы не вошли в систему и все остальные запросы нуждаются в аутентификации.

Чтобы исправить это, измените свой узор на /css/** и /images/**.

Лучшее решение для статических ресурсов WebSecurity#ignoring:

Позволяет добавлять RequestMatcher экземпляры, которые Spring Security следует игнорировать. Веб-безопасность, предоставляемая Spring Security (включая SecurityContext), не будет доступна по адресу HttpServletRequest, который соответствует. Обычно регистрируемые запросы должны быть только статическими ресурсами.Для запросов, которые являются динамическими, рассмотрите сопоставление запроса, чтобы разрешить всем пользователям.

Пример:

webSecurityBuilder.ignoring() 
// ignore all URLs that start with /resources/ or /static/ 
       .antMatchers("/resources/**", "/static/**"); 
Смежные вопросы