Referer拦截器

 

#Referer拦截
referer:
  enabled: true
  #支持配置多个域名,以,分隔。
  domains: 127.0.0.1,localhost
//Referer拦截器
//@Component
public class RefererInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(getClass());

    //是否启用拦截。默认不启用
    @Value("${referer.enabled:false}")
    private Boolean referer_enabled;
    //白名单域名。支持配置多个域名,以,分隔。
    @Value("${referer.domains:}")
    private List<String> referer_domains;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        if (referer_enabled && referer_domains.size() > 0) {
            String referer = req.getHeader("referer");
            String host = req.getServerName();

            //空referer,浏览器直接访问,放行。
            if (referer == null) {
                return true;
            }

            String refererHost;
            try {
                java.net.URL url = new java.net.URL(referer);
                refererHost = url.getHost();
            } catch (MalformedURLException e) {
                // URL解析异常,也置为404
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                resp.getWriter().write("非法请求,不是同源的访问。");
                resp.flushBuffer();
                return false;
            }

            //referer和host相同,同源的链接,放行。
            if (refererHost.equals(host)) {
                return true;
            }

            //referer和host不同。判断是否在白名单。referer在白名单,放行。
            if (referer_domains.contains(refererHost)) {
                return true;
            }

            //referer和host不同。且不在白名单。
            log.error("referer: " + referer + ", host:" + host);
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            resp.getWriter().write("非法请求,不是同源的访问。");
            resp.flushBuffer();
            return false;
        }
        return true;
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    //@Autowired
    //RefererInterceptor refererInterceptor;
    @Bean
    public RefererInterceptor refererInterceptor() {
        return new RefererInterceptor();
    }

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //referer拦截
        //registry.addInterceptor(refererInterceptor);
        registry.addInterceptor(refererInterceptor());
    }
}

 

posted @ 2022-04-03 17:14  己为  阅读(367)  评论(0编辑  收藏  举报