Angular+Spring Boot打包war部署Tomcat访问前端返回401未授权错误求助
修复方案
修正静态资源存放路径
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目录中。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); }
- 可选:添加视图控制器配置适配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"); } }
- 验证打包产物
打包后解压生成的audittool.war,确认WEB-INF/classes/static目录下存在Angular生成的index.html、js、css等文件即可重新部署。
补充说明:你所说的Postman访问正常是因为Postman缓存了之前请求携带的有效Authorization头,清空缓存后再请求就能复现401错误。
内容的提问来源于stack exchange,提问作者ananth
相关产品推荐
相关产品推荐

