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

Spring Security 如何配置允许特定主机名的访问请求

Spring Security 原生未提供直接配置域名白名单的内置API,仅有的hasIpAddress()方法仅支持IP/IP段校验。你可以通过自定义校验规则实现域名放行需求,核心是匹配HTTP请求的Host头,具体实现方式如下:

轻量实现(单域名校验)

如果仅需匹配少量固定域名,可直接在安全配置中通过access()方法编写SpEL表达式校验Host头:

class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 校验Host为localhost,自动兼容带端口的情况比如localhost:8080
                .antMatchers("/**").access("request.getHeader('Host').startsWith('localhost')")
                .anyRequest().permitAll();
    }
}

通用实现(多域名白名单)

如果需要配置多个可动态调整的白名单域名,可以自定义校验组件复用逻辑:

  1. 首先编写域名校验工具类,支持从配置文件读取白名单:
@Component
public class HostWhitelistValidator {
    // 实际使用可通过@Value注解读取application.yml配置的白名单列表
    private final List<String> allowedHosts = List.of("localhost", "your-domain.com");

    public boolean isValid(HttpServletRequest request) {
        String hostHeader = request.getHeader("Host");
        if (hostHeader == null || hostHeader.isBlank()) {
            return false;
        }
        // 提取域名部分,忽略端口
        String domain = hostHeader.contains(":") ? hostHeader.split(":", 2)[0] : hostHeader;
        return allowedHosts.contains(domain);
    }
}
  1. 在安全配置中引用自定义校验逻辑:
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private HostWhitelistValidator hostWhitelistValidator;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("@hostWhitelistValidator.isValid(request)")
                .anyRequest().permitAll();
    }
}

注意:Host头存在被伪造的风险,如果服务前置有反向代理,建议先在代理层校验Host头合法性,或者配置Spring Security的ForwardedHeaderFilter处理代理转发的真实请求信息,避免恶意请求绕过校验。

内容的提问来源于stack exchange,提问作者Saideep Ullal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:15:06