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

Add CSS file to Spring Boot + Spring Security Thymeleaf file

我想将 CSS 文件添加到我的 HTML 文件中。 当我尝试将 CSS 添加到 Spring 安全应用程序时出现问题(我处理基本的 Spring 入门内容)。我责怪 Spring 安全性,因为没有它 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 文件中。

您的模式 ../static/css 与您的亲戚 URL ../static/css/index.css 不匹配,参见 AntPathMatcher:

PathMatcher implementation for Ant-style path patterns.

Part of this mapping code has been kindly borrowed from Apache Ant.

The mapping matches URLs using the following rules:

  • ? matches one character
  • * matches zero or more characters
  • ** matches zero or more directories in a path
  • {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"

Spring Boot Reference:

By default, resources are mapped on /** but you can tune that via 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/**");
.antMatchers("/**/*.js", "/**/*.css").permitAll();

这允许 resources/static 文件夹中存在的所有 js 和 css 文件被允许请求访问。

web.ignore()最适合我。只需将以下方法添加到您的 WebSecurityConfig class.

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