Spring Boot资源服务器IP校验端点触发身份认证问题求助
问题解决:IP校验端点无需OAuth2认证仅做IP限制
问题原因
启用@EnableResourceServer后,Spring Security OAuth2默认会强制所有请求经过OAuth2令牌校验,即使配置了IP访问规则,匿名请求(未携带令牌)仍会被判定为需要完整认证。同时从日志可见,当前测试请求的IP0:0:0:0:0:0:0:1(本地IPv6回环地址)不在你配置的允许范围内,但核心需求是让该端点仅执行IP校验,不要求OAuth2认证。
解决方案
方案1:允许匿名访问并叠加IP校验
修改configure(HttpSecurity http)中的规则,先允许匿名访问目标端点,再应用IP限制表达式,确保未携带令牌的请求也能进入IP校验逻辑:
@Override public void configure(HttpSecurity http) throws Exception { http .httpBasic().disable(); http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http .csrf().disable(); http .authorizeRequests() // 允许匿名访问/locked,同时校验IP .regexMatchers(HttpMethod.GET, "\\/locked") .anonymous() .access("hasIpAddress('192.168.216.0/23') or hasIpAddress('10.4.7.59')") .antMatchers(HttpMethod.POST, "/purgePackets").hasRole(ESIGN_PURGE_BATCH) .anyRequest().permitAll(); }
方案2:让端点完全跳过OAuth2过滤器
如果希望该端点彻底不经过OAuth2的认证流程,可通过ResourceServerSecurityConfigurer忽略该端点,再单独配置IP校验:
@Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { // 让/locked跳过OAuth2资源服务器的所有过滤器 resources.ignoring().regexMatchers(HttpMethod.GET, "\\/locked"); } @Override public void configure(HttpSecurity http) throws Exception { http .httpBasic().disable(); http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http .csrf().disable(); http .authorizeRequests() // 仅对/locked做IP校验,无需OAuth2认证 .regexMatchers(HttpMethod.GET, "\\/locked").access("hasIpAddress('192.168.216.0/23') or hasIpAddress('10.4.7.59')") .antMatchers(HttpMethod.POST, "/purgePackets").hasRole(ESIGN_PURGE_BATCH) .anyRequest().permitAll(); }
额外测试提示
日志中显示的请求IP是0:0:0:0:0:0:0:1(本地IPv6回环地址),如果是本地测试,需要将该IP加入允许列表,或者切换为IPv4地址(如127.0.0.1)验证IP校验逻辑。
内容的提问来源于stack exchange,提问作者Braden Borman
相关产品推荐
相关产品推荐

