You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringSecurity中如何开放HTML页面所需静态资源的访问权限?

解决Spring Security静态资源访问被拦截的问题

嘿,我看你遇到了Spring Security拦截静态资源的问题,咱们一步步来搞定它。

首先分析下问题根源:你的HTML里用./styling.css引用样式文件,但Spring Security配置里开放的是/css/**路径,这里有两个核心问题:

  • 相对路径./可能会导致资源请求路径解析错误(比如页面在/user/home时,请求会变成/user/styling.css,完全不在你配置的/css/**范围内)
  • 你还可以通过WebSecurity直接忽略静态资源拦截,比在HttpSecurity里配置更高效

下面是具体的解决方案:

1. 修正资源引用路径与存放位置

  • 先确保你的styling.css放在Spring Boot默认的静态资源目录:src/main/resources/static/css/
  • 把HTML里的资源引用改成绝对路径(或者用Thymeleaf的语法):
    <!-- 原生HTML绝对路径 -->
    <link rel="stylesheet" type="text/css" href="/css/styling.css">
    <!-- 推荐用Thymeleaf的@{语法,自动适配上下文路径} -->
    <link rel="stylesheet" type="text/css" th:href="@{/css/styling.css}">
    
  • 你当前配置里的antMatchers("/css/**").permitAll()是正确的,只要资源路径匹配上就能生效

2. 通过WebSecurity忽略静态资源(更推荐)

在你的SpringSecurityConfig中新增configure(WebSecurity web)方法,让Spring Security完全跳过静态资源的拦截处理,这样就不用在HttpSecurity里额外配置了:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers("/css/**", "/js/**", "/images/**"); // 按需添加你的其他静态资源路径
}

这种方式更高效,因为Spring Security不会对这些路径做任何安全校验。

3. 检查现有配置的小细节

你当前的HttpSecurity配置里,.antMatchers("/css/**").permitAll()要放在.anyRequest().authenticated()之前,不过看你的代码已经做到了,这点没问题。另外注意不要把HTML代码和Java代码混在一起(你提供的代码里把HTML和SpringSecurityConfig的Java代码放一块了,记得分开存放)。

按照上面的步骤调整后,你的静态资源应该就能正常访问了。

内容的提问来源于stack exchange,提问作者Todor Dimitrov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:04