Spring Security Java配置:如何通过逻辑或组合IP与HTTP Basic Auth权限?
组合IP白名单与HTTP Basic Auth认证
你需要的是**“或”逻辑**的权限校验:请求要么来自指定的信任IP,要么通过HTTP Basic Auth认证,对吧?在你使用的Spring Security 5.0.3版本中,可以通过SpEL(Spring表达式语言)结合access()方法来实现这种复合校验逻辑,完美替代原来的两个单独配置。
下面是完整的配置代码:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; public class SecurityConfig extends WebSecurityConfigurerAdapter { // 可将IP配置移至application.properties中,此处为示例值 private String allowedIp = "123.456.789.123/32"; // 复用你已定义的自定义认证入口点 private CustomAuthenticationEntryPoint cncAuthEntryPoint; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() // 核心逻辑:信任IP直接放行,或已认证用户放行 .anyRequest().access("hasIpAddress('" + allowedIp + "') or isAuthenticated()") .and() // 保留原有HTTP Basic配置与自定义认证入口 .httpBasic() .authenticationEntryPoint(cncAuthEntryPoint); } }
关键逻辑说明:
hasIpAddress('xxx'):校验请求来源IP是否在信任列表中,支持CIDR格式(比如你用的/32表示单个具体IP)isAuthenticated():校验请求是否通过了HTTP Basic Auth认证- 用
or连接两个条件,实现满足任意一个条件即可访问的需求
扩展提示:
如果需要添加多个信任IP,直接扩展SpEL表达式即可:
// 多个IP用or依次连接 .anyRequest().access("hasIpAddress('123.456.789.123/32') or hasIpAddress('111.222.333.444/32') or isAuthenticated()")
这个配置完全适配你当前使用的Spring 5.0.4、Spring Boot 2.0.0和Spring Security 5.0.3版本,无需额外引入依赖。
内容的提问来源于stack exchange,提问作者Eike
相关产品推荐
相关产品推荐

