Spring Boot+Angular生产环境含点URL直接访问报403错误
问题分析与修复方案
核心原因
直接访问带英文句点的Angular路由(如/release/superapp/1.1.0)返回403,页面跳转却正常,本质是生产环境中Spring Boot将带点的URL判定为静态资源请求,而非前端路由请求,未转发至Angular的index.html,同时触发了权限拦截返回403。开发环境正常是因为Angular Dev Server会自动处理所有路由转发,而生产环境依赖Spring Boot处理静态资源与路由的映射。
修复步骤
1. 配置Spring Boot路由转发控制器
添加一个控制器,确保所有非API、非已存在静态资源的请求,无论是否带点,都转发到index.html:
import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; @Controller public class SpaForwardController { private final ResourceLoader resourceLoader; public SpaForwardController(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @RequestMapping(value = "/**", method = org.springframework.web.bind.annotation.RequestMethod.GET) public String forwardToIndex(HttpServletRequest request) { String requestURI = request.getRequestURI(); // 跳过API请求,交给后端接口处理 if (requestURI.startsWith("/api")) { return null; } // 检查是否为已存在的静态资源(如.js、.css、图片等) try { Resource resource = resourceLoader.getResource("classpath:static/" + requestURI); if (resource.exists() && resource.isReadable()) { return null; // 让Spring直接返回静态资源 } } catch (IOException e) { // 资源不存在,继续转发到index.html } // 其他所有请求转发到Angular入口文件 return "forward:/index.html"; } }
2. 调整Spring Security权限配置
403错误大概率是Spring Security拦截了前端路由请求,需将所有前端路由路径加入匿名访问白名单:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 允许所有前端路由匿名访问,替换为你的实际路由前缀 .antMatchers("/release/**", "/home/**", "/about/**") .permitAll() // API接口按实际需求配置权限 .antMatchers("/api/**").authenticated() .and() // 其他安全配置... .csrf().disable(); } }
3. 确认Angular生产构建配置
确保构建生产包时base-href配置正确,避免路由路径错误:
ng build --prod --base-href /
验证方法
- 重新打包Angular并部署到Spring Boot生产环境
- 直接在浏览器地址栏输入
/release/superapp/1.1.0,确认页面正常加载,无403错误 - 测试其他带点的路由(如
/release/app/2.0.1),确保均能正常访问
内容的提问来源于stack exchange,提问作者ALansmanne
相关产品推荐
相关产品推荐

