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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:36:05