Spring boot白名单ip范围
大多数在线教程都侧重于安全端点,其中IP白名单最重要。因此,他们中的大多数人描述:Spring boot白名单ip范围,spring,spring-boot,spring-security,ip,whitelist,Spring,Spring Boot,Spring Security,Ip,Whitelist,大多数在线教程都侧重于安全端点,其中IP白名单最重要。因此,他们中的大多数人描述: @Configuration public class SomeCustom implements AuthenticationProvider { // initialization of ipWhitelistRange @Override public Authentication authenticate(Authentication auth) { WebAu
@Configuration
public class SomeCustom implements AuthenticationProvider {
// initialization of ipWhitelistRange
@Override
public Authentication authenticate(Authentication auth) {
WebAuthenticationDetails details =
(WebAuthenticationDetails) authentication.getDetails();
String userIp = details.getRemoteAddress();
if(!ipWhitelistRange.contains(userIp)) {
throw new BadCredentialsException("Invalid IP Address");
}
return authentication;
}
}
然后,应将上述内容添加到:
@Configuration
@EnableWebSecurity
public class SomeSecurity extends WebSecurityConfigurerAdapter {
...
@Autowired
private SomeCustom authenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
...
}
...
}
我的用例是使用占位符路径变量定义一个完全开放的端点,如/v1/something/{path}
。
我当前的SomeSecurity
基本上就是.anyRequest().permitAll()
,现在我只想将IP范围限制添加到一个{path}
替换。例如:
/v1/something/foo
,/v1/something/bar
等应保持完全打开,只是/v1/something/special
应限制在某个IP范围内。是否可以在路径占位符上指定IP范围限制并不重要,我还可以指定一个全新的端点,我的问题更多的是无法触发IP范围验证。
当我添加.authenticated()
时,我的端点开始响应访问此资源需要完全身份验证
,并且在调试模式下,IP范围验证逻辑中的断点不会停止
换句话说,如何在不强制API客户端向用户进行身份验证的情况下触发mySomeCustom
的IP范围验证?
我知道我可以使用SecurityContext
获取用户的IP,并在我的服务逻辑中手动进行验证,但我不会这么说。
使用弹簧护套2.2.x(弹簧5.x)
编辑:由于我意识到.authenticated()
肯定会强制用户登录而不是匿名登录,并且由于我不使用任何登录,因此我的用户自动成为匿名用户,我尝试了以下操作:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/special").hasRole("ANONYMOUS")
.anyRequest().permitAll()
}
或
以上两种方法都没有触发SomeCustom
IP白名单提供程序
是否只有在使用非匿名用户时才会触发客户身份验证提供程序?能否显示您的代码?你没有发布IP限制。所有请求都只有一个身份验证。谢谢@dur的提问。我省略了代码,因为它是一个明显的代码,我根据一组IP检查IP,如
whitelistSet.contains(IP)
,无论如何,正如我提到的,我的断点在这个方法中甚至没有停止,所以它根本不会被触发。不过为了更清楚,我会加上。我认为你的代码是完整的。SpringSecurity已经支持它了。请参阅@dur nice,如果这不起作用,我会将其作为一个后备方案,只需多次添加hasIpAddress
。但是为什么不在我的SomeSecurity
中使用.addFilterAfter(新的IPWhitelistRangeFilter(),FilterSecurityInterceptor.class)
,然后在IPWhitelistRangeFilter
中,我可以做任何我想做的事情,并以401
作为响应。在过滤器链结束时,我必须考虑一些特殊的问题吗?当然,你可以使用一个过滤器,但是在你的问题中是一个<代码> AuthenticationProvider <代码>这不是一个过滤器,因此它并不总是被应用。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/special").anonymous()
.anyRequest().permitAll()
}