spring - Spring Boot 白名单 ip 范围
问题描述
大多数在线教程都侧重于无论如何安全的端点,其中 IP 白名单是最重要的。所以他们中的大多数描述:
@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()
我的端点开始响应时Full authentication is required to access this resource
,在调试模式下,IP 范围验证逻辑中的断点不会停止。
换句话说,如何在SomeCustom
不强制 API 客户端向 USER 进行身份验证的情况下触发我的 IP 范围验证?我知道我可以使用SecurityContext
来获取用户的 IP 并在我的服务逻辑中手动进行验证,但这不是我要说的想法。使用 Spring Boot 2.2.x (Spring 5.x)
编辑:因为我意识到这.authenticated()
肯定会强制执行除 ANONYMOUS 之外的用户登录,并且由于我不使用任何登录,因此我的用户自动是匿名用户,我尝试了以下操作:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/special").hasRole("ANONYMOUS")
.anyRequest().permitAll()
}
或者
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/special").anonymous()
.anyRequest().permitAll()
}
以上两者都只是通过而没有触发SomeCustom
IP白名单提供商。
是不是只有在使用非匿名用户时才触发客户身份验证提供程序?
解决方案
推荐阅读
- python - 如何使用 MIMEMultipart?
- ar.js - 如何获取图像 AR.JS 像素中的标记位置?
- aws-lambda - 如何在本地运行 lambda 函数时增加 Lambda 函数的请求超时?
- mongodb - 难以理解项目如何与 mongoDB 聚合框架一起工作
- angular - Angular 8 中模态的循环依赖
- oracle - 使用 to_date() 选择时间段
- python - 按多个条件过滤行 - 为什么这不起作用?
- android - 有没有办法在 android studio 中添加更多设备框架以在 logcat 中截屏?
- javascript - 如何递归地从嵌套的对象数组中删除特定对象?
- db2 - SQLRPGLE 程序 IBM 中的 SQLSTATE '08003'