我有一個微服務,旨在詢問不同型別和作業系統的設備,但出于一系列原因,我想將少數 IP 列入黑名單。有沒有辦法我可以做到這一點?
uj5u.com熱心網友回復:
您是否嘗試過使用 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 類可以是這樣的
@Mapper
public interface BlackListDao {
//Find records by IP
List<BlackList> findByIp(String IP);
//Add record
int addBlackList(@Param("blackList") BlackList blackList);
}
為 Spring MVC 配置 Interceptor 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);
}
uj5u.com熱心網友回復:
最好的方法是在允許它通過之前檢查它HttpFirewall是否有潛在危險。HttpServletRequestFilterChainProxy
基本上,您需要覆寫默認值StrictHttpFirewall并添加邏輯以檢查請求的源 IP 是否在 blacklist 中,例如:
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"));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414771.html
標籤:
上一篇:在單個類中使用多個事務的正確方法
下一篇:在兩列中映射div元素
