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

如何针对特定IP用户跳过Spring Security 6的身份验证?

Spring Security 6 实现IP白名单免验证+常规身份验证方案

要实现IP免验证用户和常规认证用户的区分访问,核心是通过Spring Security的请求匹配器结合IP地址规则来划分不同用户群体,以下是具体实现步骤:

1. 基础IP白名单配置

直接使用Spring Security内置的IpAddressMatcher定义允许免验证的IP范围,在SecurityFilterChain中配置访问规则:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 定义免验证IP白名单,支持单个IP、CIDR网段(如192.168.1.0/24)
    private static final String[] WHITE_LIST_IPS = {
        "127.0.0.1",
        "192.168.1.0/24",
        "10.0.0.0/8"
    };

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 匹配白名单IP的请求直接放行
                .requestMatchers(request -> isInWhiteList(request.getRemoteAddr())).permitAll()
                // 非白名单IP的请求必须经过身份验证
                .anyRequest().authenticated()
            )
            // 配置常规身份验证方式(以表单登录为例,可替换为OAuth2、HttpBasic等)
            .formLogin(form -> form
                .loginPage("/login")
                .permitAll()
            );

        return http.build();
    }

    // 校验IP是否在白名单内
    private boolean isInWhiteList(String remoteIp) {
        for (String ipPattern : WHITE_LIST_IPS) {
            if (new org.springframework.security.web.util.matcher.IpAddressMatcher(ipPattern).matches(remoteIp)) {
                return true;
            }
        }
        return false;
    }
}

2. 优化:自定义RequestMatcher(适配复杂场景)

如果需要动态加载白名单、处理代理IP等复杂逻辑,可自定义RequestMatcher:

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class IpWhiteListMatcher implements RequestMatcher {
    private final String[] allowedIps;

    public IpWhiteListMatcher(String[] allowedIps) {
        this.allowedIps = allowedIps;
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        String remoteIp = request.getRemoteAddr();
        // 可扩展逻辑:比如从数据库查询实时白名单、解析X-Forwarded-For获取真实客户端IP
        for (String ipPattern : allowedIps) {
            if (new org.springframework.security.web.util.matcher.IpAddressMatcher(ipPattern).matches(remoteIp)) {
                return true;
            }
        }
        return false;
    }
}

在SecurityConfig中替换为自定义匹配器:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    IpWhiteListMatcher ipWhiteListMatcher = new IpWhiteListMatcher(WHITE_LIST_IPS);

    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers(ipWhiteListMatcher).permitAll()
            .anyRequest().authenticated()
        )
        .formLogin(form -> form
            .loginPage("/login")
            .permitAll()
        );

    return http.build();
}

3. 关键注意事项

  • 代理IP处理:若应用部署在反向代理(Nginx、Apache)后,需配置ForwardedHeaderFilter或自定义过滤器解析X-Forwarded-For头,避免拿到代理服务器IP而非真实客户端IP。
  • 路径粒度控制:若仅需部分路径对IP白名单开放,可修改规则为.requestMatchers("/public/**").access("hasIpAddress('127.0.0.1')")。
  • 动态白名单:将白名单存储在数据库,在自定义匹配器中实时查询,可实现无需重启应用更新白名单。

内容的提问来源于stack exchange,提问作者Alok Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:52:37