将CSS文件添加到Spring Boot + Spring Security Thymeleaf文件

8

我想在我的HTML文件中添加CSS文件。

当我尝试将CSS添加到Spring Security应用程序中时(我正在基本的Spring入门内容上工作),问题出现了。我指责Spring Security,因为没有它,CSS文件可以正常加载。

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文件中。

请添加您的项目结构。这将有助于他人。谢谢。 - Priyantha
3个回答

9
您的模式 ../static/css 与您的相对URL ../static/css/index.css 不匹配,请参见 AntPathMatcher:

用于 Ant 风格路径模式的 PathMatcher 实现。

这个映射代码的一部分是从 Apache Ant 中借来的。

映射使用以下规则匹配 URL:

  • ? 匹配一个字符
  • * 匹配零个或多个字符
  • ** 匹配路径中零个或多个目录
  • {spring:[a-z]+} 将正则表达式 [a-z]+ 作为名为 "spring" 的路径变量进行匹配

Spring Boot 参考文档:

默认情况下,资源映射在 /** 上,但您可以通过 spring.mvc.static-path-pattern 进行调整。

由于您未登录且所有其他请求都需要身份验证,因此您的请求将被重定向到登录表单。

要解决此问题,请将您的模式更改为 /css/**/images/**

对于静态资源,更好的解决方案是使用 WebSecurity#ignoring:

Allows adding RequestMatcher instances that Spring Security should ignore. Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.

Example Usage:

 webSecurityBuilder.ignoring()
 // ignore all URLs that start with /resources/ or /static/
                .antMatchers("/resources/**", "/static/**");

这是适用于子文件夹的代码片段,对我很有效。感谢@Dur。 http.authorizeRequests() .antMatchers(HttpMethod.GET, "/css/", "/js/").permitAll(); - ASH

5

web.ignore() 对我来说是最好的选择。只需将以下方法添加到您的 WebSecurityConfig 类中即可。

@Override
public void configure(WebSecurity web) throws Exception {
    web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}

4
.antMatchers("/**/*.js", "/**/*.css").permitAll();

这可以允许请求访问位于resources/static文件夹中的所有js和css文件。

非常感谢。我搜索了几天关于这个问题,最终找到了最好的解决方案! - Eltac Shikhsaidov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接