Spring Security添加后静态资源加载失败返回303状态码问题
解决方案
问题根源
你遇到的303重定向问题,本质是Spring Security拦截了静态资源请求——配置里的/static/**匹配规则和实际请求路径不匹配。Spring Boot默认会把src/main/resources/static目录下的资源映射到根路径(/),比如static/js/main.js的访问路径是/js/main.js,而非/static/js/main.js,所以原来的规则根本没命中静态资源请求,导致请求被拦截后重定向到登录页。
具体修复步骤
1. 修正Security配置的权限规则
修改Security类中的securityFilterChain方法,放开静态资源的实际访问路径:
@Configuration @EnableWebSecurity public class Security { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf(Customizer.withDefaults()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(request -> { // 放开所有静态资源及上传图片的访问权限 request.requestMatchers("/js/**", "/css/**", "/images/**", "/uploads/**").permitAll() // 后台路径需要认证 .requestMatchers("/backoffice/**").authenticated() // 首页、登录页放开权限 .requestMatchers("/index/**", "/login").permitAll() // 其他所有请求需认证 .anyRequest().authenticated(); }) .formLogin(form -> form .loginPage("/login") .permitAll() ); return http.build(); } }
2. 确认Thymeleaf模板中的资源引用路径
确保模板里引用静态资源时使用根路径,避免加static前缀:
<!-- 正确写法 --> <script th:src="@{/js/main.js}"></script> <link th:href="@{/css/style.css}" rel="stylesheet"> <!-- 错误写法(需避免) --> <script th:src="@{/static/js/main.js}"></script>
3. 可选:用后缀匹配简化规则
如果静态资源类型较多,也可以直接按后缀匹配所有静态资源:
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; // 在authorizeHttpRequests中替换为: request.requestMatchers(antMatcher("/**/*.js"), antMatcher("/**/*.css"), antMatcher("/**/*.png"), antMatcher("/**/*.jpg")).permitAll()
验证修复
重启应用后,访问页面检查静态资源的请求状态码,应该返回200,页面样式和脚本可正常加载。
内容的提问来源于stack exchange,提问作者Kristijan P.
相关产品推荐
相关产品推荐

