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

Spring Security登录页面无法加载静态资源问题求助

解决Spring Security静态资源无法访问的问题

问题出在你配置的静态资源路径匹配错误。Spring Boot默认会把resources/static目录下的资源映射到根路径(/),也就是说,你访问static/css/login.css时,实际请求路径是/css/login.css,而非/static/css/login.css,所以你之前写的.requestMatchers("/static/**").permitAll()根本匹配不到实际的静态资源请求。

正确配置方式

修改securityFilterChain方法,添加对静态资源实际路径的放行规则,比如针对css、js、图片等常见静态资源类型:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
                    // 放行所有静态资源请求
                    .requestMatchers("/css/**", "/js/**", "/img/**", "/fonts/**").permitAll()
                    // 原有的接口放行规则
                    .requestMatchers("api/v1/apps/welcome", "api/v1/apps/new-user").permitAll()
                    .requestMatchers("api/v1/apps/**").authenticated())
            .formLogin(form -> form
                    .loginPage("/login")
                    .permitAll())
            .build();
}

如果你想更简洁地匹配所有静态资源(不管目录结构),也可以用后缀匹配:

.requestMatchers("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg").permitAll()

另一种更简便的方式(可选)

还可以通过WebSecurityCustomizer直接忽略静态资源的安全校验,这样Spring Security不会拦截这些请求:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web.ignoring().requestMatchers("/css/**", "/js/**", "/img/**");
}

注意:这种方式是让Spring Security完全不处理这些请求,适合纯静态资源场景;如果需要对静态资源做一些额外的安全控制(比如某些资源只允许特定角色访问),还是用第一种在authorizeHttpRequests里配置的方式更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:10:58