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

Spring Security 6.0公共资源访问配置失效,请求协助排查

问题原因分析及解决办法

核心问题1:路径匹配不精准

你在Security配置里用了requestMatchers("/hello/**").permitAll(),但控制器里的@GetMapping("hello")对应的是根路径/hello。Spring Security的/**匹配的是该路径下的所有子资源(比如/hello/test),不会匹配路径本身,所以/hello并没有被纳入permitAll的规则范围,依然会被默认的认证拦截。

核心问题2:缺少默认请求规则

你的authorizeHttpRequests配置末尾没有添加默认规则,Spring Security在遇到未明确匹配的请求时,会默认要求认证,这也是导致/hello被拦截的原因之一。

解决步骤

修改SecurityConfig中的filterChain方法,调整路径匹配并补充默认规则:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/hello", "/hello/**") // 同时匹配/hello本身和其子路径
            .permitAll()
            .requestMatchers(HttpMethod.DELETE)
            .hasRole("ADMIN")
            .requestMatchers("/admin/**")
            .hasAnyRole("ADMIN")
            .requestMatchers("/protected/**")
            .hasAnyRole("USER", "ADMIN")
            .anyRequest() // 对所有未匹配的请求,要求认证
            .authenticated()
        )
        .httpBasic()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return http.build();
}

也可以用requestMatchers("/hello*")简化匹配,它会同时覆盖/hello和/helloXXX这类路径。

修改后验证:访问/hello会直接返回"home",无需输入凭证;/admin依然只有ADMIN角色能访问,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:55:33