【问题标题】:Precedence for Basic Auth & IP white listBasic Auth & IP 白名单的优先级
【发布时间】:2019-05-01 02:40:32
【问题描述】:

我正在为 Spring Boot 应用程序中的几个内部端点设置基本身份验证。在进行基本身份验证检查之前,我有一个用例来进行 IP 白名单验证。使用 WebSecurityConfigurerAdapter 配置方法,我能够实现这一点,但是在 ip 白名单授权之前完成基本身份验证的顺序是相反的。

有没有办法让 IP 白名单优先于基本身份验证?

使用以下代码进行网络安全

return new WebSecurityConfigurerAdapter() {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
            .anyRequest()
            .access("(hasIpAddress('xx.xx.xx.xx') and isAuthenticated()")
            .and()
            .httpBasic();
    }
}

【问题讨论】:

  • 没有内置方法。但是,最简单的方法是实现您自己的自定义过滤器。只需执行javax.servlet.Filter。您可以使用 addFilterBefore 在 Spring 配置中添加过滤器。

标签: spring-boot spring-security basic-authentication


【解决方案1】:

您必须在配置中按照您想要的顺序声明。

@Component
public class IPWhiteLister implements AuthenticationProvider {
     
   Set<String> whitelist = new HashSet<String>();
 
    public CustomIpAuthenticationProvider() {
        whitelist.add("10.1.1.1");
        whitelist.add("172.1.1.1");
    }
 
    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        String userIp = details.getRemoteAddress();
        if(! whitelist.contains(userIp)){
            throw new BadCredentialsException("Invalid IP Address");
        }
        return auth;
}

并按照https://www.baeldung.com/spring-security-multiple-auth-providers 中的步骤使用多个身份验证提供程序。您还必须覆盖另一个配置方法来构建 AuthenticationManagerBuilder。 您可以通过方法 authenticationProvider 添加多个 Authentication Provider。这有点欺骗性,因为签名并没有说它允许您添加多个身份验证提供程序。

    public class ApplicationSecurity extends WebSecurityConfigurerAdapter
    {

      Logger logger = LoggerFactory.getLogger(ApplicationSecurity.class);

      @Autowired
      private IPWhiteListFilter ipWhiteListFilter;
      @Override
      protected void configure(AuthenticationManagerBuilder auth){
        auth.authenticationProvider(ipWhiteListFilter);
        // FOLLOWING is just an example
        auth.authenticationProvider(userNamePasswordAuthenticator)
      }
   ...

而不是以下代码中的行

.access("(hasIpAddress('xx.xx.xx.xx') and isAuthenticated()")

随便用

.authenticated()

【讨论】:

  • 你能说得更具体一点吗?我在问题中添加了我的代码 sn-p
猜你喜欢
  • 2022-08-16
  • 2015-03-07
  • 1970-01-01
  • 2021-05-02
  • 2012-12-04
  • 2013-05-06
  • 1970-01-01
  • 2022-08-22
  • 2014-11-25
相关资源
最近更新 更多