You need to enable JavaScript to run this app. Spring Security应用无法访问资源目录新上传图片,返回401未授权错误
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security应用无法访问资源目录新上传图片,返回401未授权错误

问题根因与修复方案

核心根因拆解

你遇到的401本质是新上传图片的请求没有匹配到Spring Security的放行规则,落到了anyRequest().authenticated()的授权逻辑下,且请求未携带合法JWT Token,因此被JWT认证入口拦截返回401。结合你的配置,常见触发原因有3个:

1. 静态资源放行路径与实际访问路径错位

WebSecurity.ignoring()的作用是将匹配路径完全排除在Spring Security过滤链之外,但规则严格基于配置的URL模式,和资源是否存在无关。你目前的配置存在明显路径不匹配:

  • 实际访问的图片路径是/resource/static/assets/img/xxx.png(单数resource开头)
  • 已配置的放行规则仅覆盖:
    • WebSecurity.ignoring():仅放行复数/resources/**
    • HttpSecurity.permitAll():仅放行复数/resources/**和不带/static前缀的/assets/img/**

启动时预置图片能正常访问,是因为这些资源被Spring Boot默认静态资源处理器提前扫描映射,碰巧匹配到了某条放行规则;运行时新上传的资源如果路径稍有差异(比如多了/static前缀),就会直接落入未放行的规则范围。


2. JWT过滤器硬编码放行规则未同步

你的jwtRequestFilter在授权环节之前执行,如果过滤器内部硬编码了放行路径列表,且没有和Spring Security的permitAll规则同步,就会出现:

  • 启动时已知的预置图片路径被硬编码放行
  • 运行时新上传的图片路径没有被硬编码匹配,过滤器直接判定无有效Token,提前返回401

3. 外部上传目录的资源映射未覆盖放行规则

如果你的上传目录是磁盘外部目录,需要确保该目录的URL映射完全被Spring Security的放行规则覆盖,否则会直接触发401。

对应修复方案

方案1:统一静态资源放行规则,消除路径错位

不要同时用WebSecurity.ignoring()和HttpSecurity.permitAll()重复配置,优先用HttpSecurity统一配置所有放行规则,确保路径和实际访问完全匹配:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        .cors().and()
        .authorizeRequests(auth -> auth
            .antMatchers(
                "/login", 
                "/api/user/register",
                "/api/password/forgot_password", 
                "/api/password/reset_password",
                // 补全所有实际用到的静态资源路径
                "/resource/static/**",
                "/resources/**",
                "/assets/img/**",
                "/api/event/",
                "/api/photography/files/**"
            ).permitAll()
            .anyRequest().authenticated()
        )
        .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

如果要使用WebSecurity.ignoring()配置完全跳过安全链的静态路径(性能更高),需要确保路径和实际访问完全一致:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers(
            "/resource/static/**",
            "/assets/**",
            "/resources/**"
        );
}

方案2:修正JWT过滤器的放行逻辑,取消硬编码

不要在jwtRequestFilter里硬编码放行路径,复用Spring Security已配置的规则,避免规则不一致:

  1. 抽取公共的放行路径匹配器:
// 统一维护所有放行路径,避免规则不同步
private static final RequestMatcher PERMIT_ALL_MATCHER = new OrRequestMatcher(
    new AntPathRequestMatcher("/login"),
    new AntPathRequestMatcher("/api/user/register"),
    new AntPathRequestMatcher("/api/password/forgot_password"),
    new AntPathRequestMatcher("/api/password/reset_password"),
    new AntPathRequestMatcher("/resource/static/**"),
    new AntPathRequestMatcher("/resources/**"),
    new AntPathRequestMatcher("/assets/img/**"),
    new AntPathRequestMatcher("/api/event/"),
    new AntPathRequestMatcher("/api/photography/files/**")
);
  1. JWT过滤器优先判断放行规则,匹配则直接跳过Token校验:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // 放行路径直接跳过JWT校验
    if (PERMIT_ALL_MATCHER.matches(request)) {
        filterChain.doFilter(request, response);
        return;
    }
    // 原有JWT校验逻辑
    String jwt = getTokenFromRequest(request);
    if (StringUtils.hasText(jwt) && jwtTokenValidator.validate(jwt)) {
        // 加载用户认证信息
    }
    filterChain.doFilter(request, response);
}
  1. HttpSecurity配置直接复用该匹配器,避免重复配置:
.authorizeRequests(auth -> auth
    .requestMatchers(PERMIT_ALL_MATCHER).permitAll()
    .anyRequest().authenticated()
)

方案3:补全外部上传目录的映射与放行规则

如果你的新图片存储在磁盘外部目录,需要先确认该目录的资源映射路径(比如/upload/img/**),再把该路径加入上述PERMIT_ALL_MATCHER列表即可。

额外优化建议

  • 删除原配置中重复调用的空authorizeRequests(),该配置没有实际作用,只会增加复杂度
  • Spring Security 5.8+版本已废弃WebSecurity.ignoring()的静态资源配置方式,可使用PathRequest.toStaticResources()自动放行Spring Boot默认静态资源路径,无需手动维护:
.webSecurity(web -> web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 14:15:05