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
相关产品推荐
相关产品推荐

