【问题标题】:Spring Security - whitelist IP rangeSpring Security - 白名单IP范围
【发布时间】:2017-06-29 03:01:15
【问题描述】:

我查看的大量资源和 stackoverflow 问题提供了使用 .xml 文件的答案:

我想知道的是,是否可以在不使用 XML 配置的情况下使用 Spring Security 将 IP 地址范围列入白名单?

下面是我控制器中的一个简单方法:

@RequestMapping(value = "/makeit", method = RequestMethod.GET)
@ResponseBody
//@PreAuthorize("hasIpAddress('192.168.0.0/16')")
public String requestData() {

    return "youve made it";
}

我已经为安全配置创建了一个单独的类,但它没有太多,我只是为 EnableGlobalMethodSecurity 注释创建了它 - 这样我就可以使用 @PreAuthorize 注释(来自这里的答案:@ 987654324@)。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
            .authorizeRequests()
                .anyRequest().access("hasIpAddress('0.0.0.0/0')");

        /*http
            .authorizeRequests()
                .anyRequest().hasIpAddress("0.0.0.0/0");*/

        /*http
            .authorizeRequests()
                .antMatchers("/**").hasIpAddress("0.0.0.0/0");*/

        /*http
            .authorizeRequests()
                .antMatchers("/**").access("hasIpAddress('0.0.0.0/0')");*/

        /*http
            .authorizeRequests()
                .anyRequest().access("hasIpAddress('0.0.0.0/0')");*/

    }
}

但是,当我尝试时,它响应(通过 POSTMAN):

{
  "timestamp": 1486743507520,
  "status": 401,
  "error": "Unauthorized",
  "message": "Full authentication is required to access this resource",
  "path": "/makeit"
}

补充事实:

我的 IP 地址在此范围内。我正在使用 Spring 1.3.1 版(我相信 Spring Security 是 4.0.3)。

【问题讨论】:

  • @dur 感谢您的反馈。所以我已经更新了一点,但最初(当我发布这个问题时),我的假设是在 websecurity 配置文件中没有太多,因为我希望通过任何请求但只保留一种方法(在这种情况下 - /makeit ) 受 IP 地址限制。所有链接的 URL 都提供了特定用户的示例(使用 inMemoryAuthentication() 构建),但没有一个只有 IP 地址。在上面的安全配置类示例中,我已经向所有人开放。
  • 即使我删除了方法级别的注释,理论上它应该对任何人开放(0.0.0.0/0)但它仍然拒绝访问。我也尝试过其他解决方案(在上面的代码中注释掉了)
  • @dur 是的,这适用于经过身份验证的用户(使用 AuthenticationManagerBuilder)。但是,经过进一步检查,您似乎对 IP 地址是正确的。Tomcat 在调用 localhost 时使用 IPv6 地址。因此,0.0.0.0/0 不是有效格式。因此,当我将其更改为接受 IPv6(没有子网)时,它可以正常工作(::1)。有趣的是,如果您使用 127.0.0.1(本地测试时),它使用它的 IPv4 地址并且原始方式有效......所以这是 Tomcat 的问题,而不是 Spring 安全性。

标签: java security spring-mvc spring-boot spring-security


【解决方案1】:

所以在@Dur 的帮助下,我们能够解决问题。问题不在于 Spring Boot(上面一切正常),但问题是当用户在本地访问 Spring App(localhost:8080)时,localhost 使用 IPv6 地址,并且上面的代码允许访问 IPv4 地址。

您需要通过将 IPv4 地址更改为 IPv6(或任何 Tomcat 默认设置)来更改 SpringSecurityConfig 文件,或者您可以更改访问应用程序的方式(通过转到 127.0.0.1:8080)。

注意 - 这仅用于本地测试。您需要测试并获取将访问您的应用的用户/服务的 IP 地址。

简而言之,您可以通过使用上述代码而不使用 AuthenticationManagerBuilder 将 IP 范围列入白名单。

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2014-01-16
    • 2013-10-20
    • 2018-01-22
    • 2013-05-11
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多