首页 > 解决方案 > 如何在 Spring Boot 中使用 IPwhitelisting 和 OAuth2?

问题描述

我在我的 Spring Boot 应用程序中使用 OAuth2,并且我想将 IP 白名单用于 IP 地址范围。即我想让白名单用户在不提供令牌的情况下访问特定资源。我有大量列入白名单的 IP,并且我正在使用 Oauth2 令牌验证,因此我有一个资源服务器。我想首先使用 IP 白名单,如果失败,用户应该拥有有效的令牌才能访问资源。你能告诉我我该怎么做吗?

标签: springspring-bootspring-mvcspring-securityspring-security-oauth2

解决方案


在 Spring Security 中,您可以使用安全配置类中的方法 hasIpAddress 配置您的特定端点和白名单。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/api/**").hasIpAddress("11.11.11.11")
          .anyRequest().authenticated()
          .and()
          .formLogin().permitAll();
    }
}

如果您有多个 IP 地址,那么您可以通过这种方式使用

http
    .authorizeRequests()
    .antMatchers("/api/**").access(
            "hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')")

对于资源服务器,您可以在 @EnableResourceServer 类中执行此操作,并且可以使用相同的配置方法来设置 Ipwhitelisting,如下所示

    @Configuration
    @EnableResourceServer
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(new OAuthRequestedMatcher())
                    .anonymous().disable().authorizeRequests();
    http
    .authorizeRequests()
    .antMatchers("/api/**").access("hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')");
        }
    }

现在,既然您已经提到您有许多 IP 地址,您可以在属性文件 (application.properties) 中列出一个列表,并且在应用程序启动时,您可以遍历这些以构建必须在访问方法中传递的参数字符串.


推荐阅读