Spring Boot Security 3.2.1集成JWT后HTML页面返回403求助
问题排查与解决方案
1. 核对Security Config的资源放行规则
Spring Security 3.x的配置逻辑和旧版本有差异,重点确认authorizeHttpRequests()的规则顺序和路径匹配:
- 放行规则必须放在
anyRequest().authenticated()之前,否则会被全局认证规则覆盖 - 确保路径通配符覆盖到你的HTML资源,比如
/expensemanager/html/**
示例正确配置片段:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 放行所有HTML相关路径 .requestMatchers("/expensemanager/html/**").permitAll() // 其他接口需JWT认证 .anyRequest().authenticated() ) // JWT场景需设置无状态会话 .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 静态资源访问通常需关闭CSRF,或针对路径配置豁免 .csrf(csrf -> csrf.disable()); return http.build(); } }
2. 检查Resource Controller的映射逻辑
确认你的资源控制器没有和Security规则冲突,或路径映射错误:
- 如果HTML文件放在
src/main/resources/static/html/下,可通过WebMvcConfigurer直接映射静态资源 - 避免控制器映射和静态资源路径重叠
示例配置:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/expensemanager/html/**") .addResourceLocations("classpath:/static/html/"); } }
3. 排查JWT过滤器的拦截范围
若自定义了JWT认证过滤器,需跳过静态资源路径的校验:
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String requestURI = request.getRequestURI(); // 跳过HTML资源的JWT校验 if (requestURI.startsWith("/expensemanager/html/")) { filterChain.doFilter(request, response); return; } // 剩余JWT认证逻辑... }
4. 查看403的具体原因
开启Spring Security调试日志定位问题,在application.properties中添加:
logging.level.org.springframework.security=DEBUG
启动项目后访问HTML页面,通过日志确认是权限不足、认证失败还是路径匹配错误。
5. 校验请求路径的一致性
Spring Security路径匹配默认大小写敏感,确保请求URL和配置中的路径完全一致(比如/expensemanager/html/和/ExpenseManager/html/会被视为不同路径)。
内容的提问来源于stack exchange,提问作者D C Sahu
相关产品推荐
相关产品推荐

