首页 > 解决方案 > Spring Boot 白名单 ip 范围

问题描述

大多数在线教程都侧重于无论如何安全的端点,其中 IP 白名单是最重要的。所以他们中的大多数描述:

@Configuration
public class SomeCustom implements AuthenticationProvider {

    // initialization of ipWhitelistRange

    @Override
    public Authentication authenticate(Authentication auth) {
        WebAuthenticationDetails details = 
                           (WebAuthenticationDetails) authentication.getDetails();
        String userIp = details.getRemoteAddress();
        if(!ipWhitelistRange.contains(userIp)) {
            throw new BadCredentialsException("Invalid IP Address");
        }

        return authentication;      
    }
}

那么以上内容应添加到:

@Configuration
@EnableWebSecurity
public class SomeSecurity extends WebSecurityConfigurerAdapter {
    ...
    @Autowired
    private SomeCustom authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .anyRequest().authenticated()
          ...
    }
    ...
}

我的用例是我有一个使用占位符路径变量定义的完全开放的端点,例如/v1/something/{path}. 我的当前SomeSecurity基本上只是.anyRequest().permitAll(),现在我只想将 IP 范围限制添加到其中一个{path}替换中。例如: /v1/something/foo/v1/something/bar应该保持完全开放,只是/v1/something/special应该限制在某个IP范围内。是否可以在路径占位符上指定 IP 范围限制并不重要,我还可以指定一个全新的端点,我的问题更多是我无法触发 IP 范围验证。当我添加.authenticated()我的端点开始响应时Full authentication is required to access this resource,在调试模式下,IP 范围验证逻辑中的断点不会停止。

换句话说,如何在SomeCustom不强制 API 客户端向 USER 进行身份验证的情况下触发我的 IP 范围验证?我知道我可以使用SecurityContext来获取用户的 IP 并在我的服务逻辑中手动进行验证,但这不是我要说的想法。使用 Spring Boot 2.2.x (Spring 5.x)

编辑:因为我意识到这.authenticated()肯定会强制执行除 ANONYMOUS 之外的用户登录,并且由于我不使用任何登录,因此我的用户自动是匿名用户,我尝试了以下操作:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/special").hasRole("ANONYMOUS")
      .anyRequest().permitAll()
}

或者

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/special").anonymous()
      .anyRequest().permitAll()
}

以上两者都只是通过而没有触发SomeCustomIP白名单提供商。

是不是只有在使用非匿名用户时才触发客户身份验证提供程序?

标签: springspring-bootspring-securityipwhitelist

解决方案


推荐阅读