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

Spring Boot添加Web Security后访问静态页面出现403 Forbidden错误

解决Spring Boot添加Security后根路径403禁止访问问题

你的问题核心是Spring Security拦截了根路径(/)和静态资源的访问,同时IndexController的写法也不符合预期:

  • 当前Security配置仅对部分/api路径定义了认证规则,但未明确放行根路径与静态资源,Spring Security默认会拦截所有未匹配规则的请求并拒绝访问
  • 你使用@Controller直接返回字符串的写法错误,Spring MVC会将该字符串当作视图名去查找,而非直接返回文本,这也和你要访问index.html的需求不符

方案1:放行根路径与静态资源(推荐,无需额外Controller)

修改SecuritySettings中的configure(HttpSecurity http)方法,补充静态资源与根路径的放行规则,同时补全配置逻辑:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // 开启CORS并关闭CSRF
    http = http.cors().and().csrf().disable();

    // 禁用会话管理,适配JWT无状态模式
    http = http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();

    // 配置权限规则
    http.authorizeRequests()
            // 放行根路径与所有静态资源
            .antMatchers("/", "/static/**", "/css/**", "/js/**", "/images/**").permitAll()
            // API接口的认证规则
            .antMatchers("/api/accounts/create-user").authenticated()
            .antMatchers("/api/accounts/me").authenticated()
            .antMatchers("/api/payments").hasAuthority("client")
            // 其他请求需认证(可根据需求调整)
            .anyRequest().authenticated();

    // 必须添加JWT过滤器到认证流程,否则Token解析逻辑不生效
    http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}

说明:

  • .antMatchers("/", "/static/**", ...).permitAll() 明确允许未认证用户访问根路径与静态资源,src/main/resources/static/index.html即可直接被访问
  • 补全addFilterBefore逻辑,确保JWT过滤器参与认证流程,这是你之前代码缺失的关键环节

方案2:修正IndexController(若需通过Controller处理根路径)

如果一定要通过Controller接管根路径,需调整写法以符合Spring MVC规则:

方式A:跳转至index.html视图

@Controller
public class IndexController {
    @RequestMapping("/")
    public String renderLandingPage() {
        // 返回视图名,Spring Boot会自动匹配static下的index.html
        return "index";
    }
}

方式B:直接返回文本内容

@RestController // 等价于@Controller + @ResponseBody
public class IndexController {
    @RequestMapping("/")
    public String renderLandingPage() {
        return "Welcome to the servspace";
    }
}

注意:无论哪种方式,都需要在Security配置中放行根路径"/"


额外检查项

  • 确认JwtFilter正确实现OncePerRequestFilter,并能正常解析Token、设置认证上下文
  • 检查src/main/resources/static/index.html的路径与文件名无拼写错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:07:54