![](/img/trans.png)
[英]SpringBoot microservice How to set properties in application context using java configuration
[英]blacklisting a set of ipAdresses in a microservice created using java and SpringBoot framework
我有一個微服務,旨在詢問不同類型和操作系統的設備,但出於一系列原因,我想將少數 IP 列入黑名單。 有沒有辦法我可以做到這一點?
您是否嘗試過使用 HandlerInterceptor 接口?
與 WebMvcConfigurerAdapter 結合使用。 這應該可以完成這項工作。
像這樣的東西,這里不是確切的工作代碼
//Call after request processing, but before the view is rendered (after controller method call)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);
List<BlackList> blackLists = blackListDao.findByIp(ip);
if (blackLists == null || blackLists.size() == 0){
urlHandle(httpServletRequest, 5000, 10);
} else {
//Forced control jump
modelAndView.setViewName("/errorpage/error.html");
}
}
BlackListDao class 可以是這樣的
@Mapper
public interface BlackListDao {
//Find records by IP
List<BlackList> findByIp(String IP);
//Add record
int addBlackList(@Param("blackList") BlackList blackList);
}
為 spring MVC 配置攔截器 Webmvcconfigureradapter。
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean // inject our interceptor as bean
public HandlerInterceptor getMyInterceptor(){
return new URLInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//Multiple interceptors form an interceptor chain
//Addpathpatterns is used to add interception rules. Here we assume that all links after interception / URL
//Excludepathpatterns user exclusion
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/url/**");
super.addInterceptors(registry);
}
最好的方法是在HttpFirewall
中檢查它,它可以在通過FilterChainProxy
允許它到 go 之前檢查HttpServletRequest
是否存在潛在危險。
基本上,您需要覆蓋默認的StrictHttpFirewall
並添加邏輯以檢查請求的源 IP 是否在黑名單中,例如:
public class MyFirewall extends StrictHttpFirewall {
private Set<String> backlistIPs;
public MyFirewall(Set<String> backlistIPs){
this.backlistIPs = backlistIPs;
}
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
String sourceIp = getClientIpAddress(request);
if(backlistIPs.contains(sourceIp)){
throw new RequestRejectedException("IP is blacklisted");
}
return super.getFirewalledRequest(request);
}
}
注意:請參閱此處了解如何實現 getClientIpAddress()
然后配置使用它:
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(new MyFirewall(Set.of("123.123.123.123" ,"123.123.123.124"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.