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

Spring Security:同一URL仅对POST请求启用Basic认证,允许GET请求

解决方案:针对指定路径的特定请求方法设置权限规则

完全可以实现这个需求,只需要修改SecurityFilterChain的配置,针对/customers/**路径的不同请求方法分别设置权限规则即可。

修改后的完整配置代码如下:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            // 允许GET请求直接访问/customers/**路径,无需认证
            .requestMatchers(HttpMethod.GET, "/customers/**")
            .permitAll()
            // 仅对POST请求的/customers/**路径要求ADMIN角色
            .requestMatchers(HttpMethod.POST, "/customers/**")
            .hasRole("ADMIN")
            // 其他所有请求都需要认证
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
        return http.build();
    }
}

配置说明

  • requestMatchers(HttpMethod.GET, "/customers/**").permitAll():明确指定/customers/**路径下的所有GET请求无需认证,直接允许访问
  • requestMatchers(HttpMethod.POST, "/customers/**").hasRole("ADMIN"):限定/customers/**路径下的POST请求必须由拥有ADMIN角色的用户发起
  • anyRequest().authenticated():除了上述已配置的GET请求外,其他所有请求都需要通过认证才能访问
  • 保留原有的httpBasic()认证方式,确保需要认证的请求采用HTTP基础认证流程

内容的提问来源于stack exchange,提问作者stelios.anastasakis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:35:16