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

Angular+Spring Boot打包war部署Tomcat访问前端返回401未授权错误求助

修复方案

  1. 修正静态资源存放路径
    Spring Boot默认只会扫描src/main/resources/static、src/main/resources/public、src/main/resources/META-INF/resources目录下的静态资源,你当前将Angular dist产物直接放在src/main/resources根目录,不会被识别为可直接访问的静态资源。
    操作:在src/main/resources下新建static目录,将dist下所有文件移动到该static目录中。

  2. Spring Security添加静态资源放行规则
    你当前的安全配置仅放开了/authenticate接口和OPTIONS类型请求,包括首页index.html、js、css、图片等所有静态资源都在拦截范围内,所以直接访问会返回401。
    修改SecurityConfig类的configure(HttpSecurity http)方法,新增静态资源放行规则:

protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and().
                authorizeRequests()
                // 放行首页和所有静态资源
                .antMatchers("/", "/*.html", "/*.js", "/*.css", "/*.ico", "/assets/**").permitAll()
                .antMatchers("/authenticate")
                .permitAll().antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll().anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
  1. 可选:添加视图控制器配置适配Angular路由
    如果存在Angular路由刷新后404的问题,新增Web配置类即可解决:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
        registry.addViewController("/**/{path:[^\\.]*}").setViewName("forward:/index.html");
    }
}
  1. 验证打包产物
    打包后解压生成的audittool.war,确认WEB-INF/classes/static目录下存在Angular生成的index.html、js、css等文件即可重新部署。

补充说明:你所说的Postman访问正常是因为Postman缓存了之前请求携带的有效Authorization头,清空缓存后再请求就能复现401错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:18:03