大多数在线教程都将重点放在安全端点上,其中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
进行响应,并且在DEBUG模式下,IP范围验证逻辑中的断点没有停止。
换句话说,如何在不强制API的客户端向USER进行身份验证的情况下触发SomeCustom
的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白名单提供者。
是否可能仅在使用非匿名用户时才触发客户身份验证提供者?