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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:40:46