Spring Security 6中HttpSecurity的.not()方法官方替代方案是什么?
Spring Security 6中授权表达式的官方否定方式
在Spring Security 5中,我们可以通过not()方法对授权规则取反,示例代码如下:
http.antMatcher("/**") .authorizeRequests() .antMatchers("/").not().hasRole("INVITED") .antMatchers("/forgot-password").not().authenticated()
Spring Security 6移除了not()方法,官方提供了两种核心的否定实现方式:
1. 通用方式:SpEL表达式结合access()方法
这是最灵活的替代方案,通过SpEL的!运算符对原授权逻辑取反,完全覆盖not()的功能:
http.securityMatcher("/**") .authorizeHttpRequests((authorize) -> authorize .requestMatchers("/").access("!hasRole('INVITED')") .requestMatchers("/forgot-password").access("!isAuthenticated()") )
2. 场景化替代方法
针对常见的否定场景,Spring Security 6提供了更直观的内置方法:
- 替代
not().authenticated():如果需求是仅允许匿名(未认证)用户访问,可直接使用anonymous()方法:.requestMatchers("/forgot-password").anonymous() - 若需排除单个角色,也可通过
hasAnyRole()列出所有允许的角色,但该方式仅适用于角色数量较少的场景,灵活性不如SpEL表达式。
内容的提问来源于stack exchange,提问作者OrangeDog
相关产品推荐
相关产品推荐

