如何在Spring Security中允许匿名访问/decks/{id}端点
Spring Security 端点权限配置调整方案
要实现你需要的权限规则,只需在原有authorizeRequests()块中添加针对HTTP方法和具体路径的匹配规则,注意规则顺序(Spring Security会自上而下匹配,更具体的规则要放在前面)。
修改后的配置代码如下:
import org.springframework.http.HttpMethod; @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() // 允许匿名访问单卡组视图 .antMatchers(HttpMethod.GET, "/decks/{id}").permitAll() // 需认证才能访问用户所有卡组视图 .antMatchers(HttpMethod.GET, "/decks").authenticated() // 需认证才能访问卡组编辑视图 .antMatchers(HttpMethod.GET, "/decks/{id}/edit").authenticated() // 原有无需认证的端点保留 .antMatchers("/", "/registration", "/css/**", "/images/**", "/static/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .logoutSuccessUrl("/") .permitAll(); return httpSecurity.build(); }
关键说明:
- 通过
HttpMethod.GET指定规则仅对GET请求生效,避免影响同路径下其他HTTP方法的权限控制 - 路径匹配顺序优先级:
/decks/{id}比/decks更具体,必须放在前面,否则通用路径规则会先匹配到/decks/123这类请求,导致匿名访问规则失效 - 保留原有静态资源、注册页等无需认证的规则,保障前端基础功能正常访问
内容的提问来源于stack exchange,提问作者Артём Власов
相关产品推荐
相关产品推荐

