Spring Security – 白名单IP范围
我查看过的很多资源和stackoverflow问题都提供了使用.xml
文件的答案:
-
使用Spring Security的IPfilter
-
Spring Security 4 Method security using @PreAuthorize,@PostAuthorize, @Secured, EL
-
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-namespace.html#nsa-gms
我想知道的是,如果可以在不使用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
注释(来自这里的答案: @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')");*/ } }
但是,当我尝试时,它回复了(通过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的帮助下,我们能够解决问题。 问题不在于Spring Boot(上面一切正常)但问题是当用户在本地访问Spring App(localhost:8080)时,localhost使用IPv6地址,上面的代码允许访问IPv4地址。
您需要通过将IPv4地址更改为IPv6(或Tomcat默认设置)来更改SpringSecurityConfig文件,或者您可以更改访问应用程序的方式(转到127.0.0.1:8080)。
注意 – 这仅适用于本地测试。 您需要测试并获取将访问您的应用的用户/服务的IP地址。
简而言之,您可以使用上面的代码将IP范围列入白名单,而无需使用AuthenticationManagerBuilder。