启用Spring Security后style.css无法加载,如何恢复?
解决Spring Security启用后style.css无法加载的问题
问题原因
- 当前
WebSecurityCustomizer仅忽略了/css/**和/resources/**路径,但实际请求的是根路径下的/style.css,该路径未被Spring Security放行,导致请求被拦截后返回错误的MIME类型(application/json)。 - 静态资源的存放路径与请求路径不匹配,Spring MVC无法定位到对应的资源文件。
解决方案
方案1:调整Spring Security忽略的路径
修改WebSecurityCustomizer配置,直接将/style.css加入忽略列表,或用通配符匹配所有CSS文件:
@Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**", "/css/**", "/style.css"); }
更通用的写法(匹配所有后缀为css的文件):
@Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**", "/css/**", "/**/*.css"); }
方案2:调整静态资源存放路径
将style.css移动到src/main/resources/static/css/目录下,之后通过/css/style.css路径引用该文件,即可匹配当前配置中忽略的/css/**路径。
方案3:在SecurityFilterChain中放行静态资源路径
虽然WebSecurityCustomizer忽略的请求不会经过SecurityFilterChain,但可额外在authorizeHttpRequests中添加放行规则,确保万无一失:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/acthasform/", "/resources/**", "/style.css", "/css/**").permitAll() .requestMatchers("/insert", "/delete", "/update", "/create").hasRole("ROLE_ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .successHandler(successHandler) .usernameParameter("username") .passwordParameter("password") .and() .logout() .permitAll() .and() .exceptionHandling() .accessDeniedPage("/403"); return http.build(); }
验证步骤
- 重启应用后,检查控制台是否仍有
No mapping for GET /style.css错误。 - 查看浏览器开发者面板,确认style.css请求状态为200,且MIME类型显示为
text/css。
内容的提问来源于stack exchange,提问作者Natasha
相关产品推荐
相关产品推荐

