英文:
How to do IP whitelisting in Spring Boot 3.1.0?
问题
我们将Spring Boot从2.6.0升级到3.1.0。下面的IP白名单不起作用,因为许多方法已被弃用。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasIpAddress("192.0.0.1")
.and()
.csrf().disable();
}
}
我不知道如何将IP传递给下面的代码以进行白名单设置。
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> {
auth.requestMatchers("/**");
auth.requestMatchers("","");
auth.anyRequest().authenticated();
})
.httpBasic(withDefaults()).build();
}
英文:
We did Spring Boot upgrade to 3.1.0 from 2.6.0. The below IP whitelisting doesn't work as many of the methods are deprecated.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasIpAddress("192.0.0.1")
.and()
.csrf().disable();
}
}
I am not able to figure out how to pass IP to whitelist to below code.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth-> {auth.requestMatchers("/**");
auth.requestMatchers("","");
auth.anyRequest().authenticated();})
.httpBasic(withDefaults()).build();
}
答案1
得分: 1
这是在迁移至authorizeHttpRequests()
后出现的错误,但Spring框架团队已在新版本中修复了它。
英文:
This was a bug after migration to authorizeHttpRequests()
but Spring Framework Team have fixed it into new version.
答案2
得分: 0
你可以创建一个过滤器并编写逻辑来从请求中获取IP并进行过滤。
@Component
@Order(1)
public class IpFilter implements Filter {
@Value("${allowed.ip:}")
private String whitelistedIp;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String ip = req.getRemoteAddr();
if (!ip.equals(whitelistedIp)) {
// 如果需要,可以更新逻辑
req.reset();
return;
}
chain.doFilter(request, response);
}
}
请注意,上述代码中的 @Value
注解应该是 @Value("${allowed.ip:}")
,而不是 @value("${allowed.ip:}")
。
英文:
You can create a filter and write logic to get IP from request and filter it
@Component
@Order(1)
public class IpFilter implements Filter {
@value("${allowed.ip:}")
private String whitelistedIp;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String ip = req.getRemoteAddr();
if (!ip.equals(whitelistedIp) {
// Update the logic if you want
req.reset();
return;
}
filterChain.doFilter(request, response);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论