我查看过的许多资源和 stackoverflow 问题都提供了使用 .xml
文件的答案:
我想知道的是,是否可以在不使用 XML 配置的情况下使用 Spring Security 将 IP 地址范围列入白名单?
下面是我的 Controller 中的一个简单方法:
@RequestMapping(value = "/makeit", method = RequestMethod.GET)
@ResponseBody
//@PreAuthorize("hasIpAddress('192.168.0.0/16')")
public String requestData() {
return "youve made it";
}
我已经为安全配置创建了一个单独的类,但它没有太多内容,我只是为 EnableGlobalMethodSecurity
注释创建了它 - 这样我就可以使用 @PreAuthorize
注释(来自此处的答案:@PreAuthorize annotation not working spring security)。
@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 地址。
简而言之,您可以使用上面的代码在没有 AuthenticationManagerBuilder 的情况下将 IP 范围列入白名单。
关于java - Spring Security - 白名单IP范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164876/