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(); } }
通用实现(多域名白名单)
如果需要配置多个可动态调整的白名单域名,可以自定义校验组件复用逻辑:
- 首先编写域名校验工具类,支持从配置文件读取白名单:
@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); } }
- 在安全配置中引用自定义校验逻辑:
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
相关产品推荐
相关产品推荐

