Spring Security - 白名单IP范围

rj2*_*700 7 java security spring-mvc spring-security spring-boot

我查看过的很多资源和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";
}
Run Code Online (Sandbox Code Playgroud)

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

@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')");*/

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试时,它回复了(通过POSTMAN):

{
  "timestamp": 1486743507520,
  "status": 401,
  "error": "Unauthorized",
  "message": "Full authentication is required to access this resource",
  "path": "/makeit"
}
Run Code Online (Sandbox Code Playgroud)

其他事实:

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

rj2*_*700 6

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

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

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

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


归档时间:

查看次数:

10330 次

最近记录:

8 年,10 月 前