zoukankan      html  css  js  c++  java
  • Springboot拦截器实现IP黑名单

    Springboot拦截器实现IP黑名单

    一·业务场景和需要实现的功能

    以redis作为IP存储地址实现。
    
    业务场景:针对秒杀活动或者常规电商业务场景等,防止恶意脚本不停的刷接口。
    
    实现功能:写一个拦截器拦截掉黑名单IP,额外增加一个接口,将ip地址添加到redis中,并且返回redis中当前全部ip
    

    二·Springboot中定义一个拦截器

    
    @Order(0)
    @Aspect
    @Component
    public class AopInterceptor {
    
    
        /**
         * 定义拦截器规则
         */
        @Pointcut("execution(* com.test.test.api.controller.test.test.*(..))")
        public void pointCut() {
        }
    
          /**
         * 拦截器具体实现
         *
         * @throws Throwable
         */
        @Around(value = "pointCut()")
        public Object around(ProceedingJoinPoint point) throws Throwable {
            try {
    
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                //判断是否为黑名单用户
                String ip = getIpAddress(request);
                if (checkIpBlack(ip)) {
                    //ip在黑名单中返回false
                    //return false;
                    DefaultResponse defaultResponse = new DefaultResponse();
                    defaultResponse.setCode(-1);
                    defaultResponse.setMessage("ip在黑名单中,拒绝访问.");
                    SysLogHelper.log("IpBlackAopInterceptor", "当前请求ip" + ip, "ip在黑名单中,拒绝访问");
                    return defaultResponse;
                } else {
                    //ip不在黑名单中返回true
                    SysLogHelper.log("IpBlackAopInterceptor", "当前请求ip" + ip, "ip正常,允许访问");
                    return point.proceed();
                }
    
    
            } catch (Exception e) {
                e.printStackTrace();
                SysLogHelper.error("IpBlackAopInterceptor黑名单拦截异常:", ExceptionUtils.getMessage(e) + "详细" + ExceptionUtils.getStackTrace(e), null);
            }
            return point.getArgs();
        }
    
        //对比当前请求IP是否在黑名单中,注意(对比黑名单ip存放在redis中)
        public boolean checkIpBlack(String ip) throws Exception {
            IpBlackBody body = new IpBlackBody();
            body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
            if (body != null) {
                for (int i = 0; i < body.getIp().length; i++) {
                    if (body.getIp()[i].equals(ip))
                        return true;
                }
            }
            return false;
        }
    
    }
    

    三·获取请求主机IP地址

     public final static String getIpAddress(HttpServletRequest request)
                throws IOException {
            // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
    
            String ip = request.getHeader("x-forwarded-for");
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
            } else if (ip.length() > 15) {
                String[] ips = ip.split(",");
                for (int index = 0; index < ips.length; index++) {
                    String strIp = (String) ips[index];
                    if (!("unknown".equalsIgnoreCase(strIp))) {
                        ip = strIp;
                        break;
                    }
                }
            }
    
            return ip;
        }
    

    四·扩展接口,实现将黑名单IP写入redis当中,并返回当前所有黑名单IP

    @RestController
    public class IpBlackController {
    
        @Autowired(required = false)
        private CacheHelper cacheHelper;
    
        @PostMapping("/testIpBlack")
        public IpBlackBody IpBlack(@RequestBody IpBlackBody ipBlackBody) throws Exception {
    
            IpBlackBody body = new IpBlackBody();
            body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
    
            if (body != null) {
                //拼接当前IP与redis中现有ip
                linkArray(body.getIp(), ipBlackBody.getIp());
                //将数据赋给body
                body.setIp(linkArray(body.getIp(), ipBlackBody.getIp()));
                //setex中第二个参数时间为S,根据业务场景相应调整,此处我设置为一天
                //将body中拼接后的ip地址数据写入redis中
                cacheHelper.setex("IpBlack:ips", 86400, body);
    
            } else {
                cacheHelper.setex("IpBlack:ips", 86400, ipBlackBody);
                body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
                return body;
            }
            return body;
        }
    
        //拼接两个String[]的方法
        public static String[] linkArray(String[] array1, String[] array2) {
    
            List<String> list = new ArrayList<>();
            if (array1 == null) {
                return array2;
            }
            if (array2 == null) {
                return array1;
            }
            for (int i = 0; i < array1.length; i++) {
                list.add(array1[i]);
            }
            for (int i = 0; i < array2.length; i++) {
                list.add(array2[i]);
            }
            String[] returnValue = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
    
                returnValue[i] = list.get(i);
            }
            return returnValue;
        }
    
    }
    
    
    总结:首先根据需要拦截的controller拦截响应请求controller层,然后根据编写相关拦截器的具体实现,其中包含两部主要操作:
    1.获取到远程请求主机的实际ip地址
    2.对比当前ip是否在黑名单中(此次操作需要读取redis中的黑名单ip列表)
    然后根据当前需求增加了一个redis接口,实现将需要封禁的IP地址增加到redis黑名单中并返回当前所有的黑名单IP地址。
    至此:至此springboot通过拦截器实现拦截黑名单功能已经实现。
  • 相关阅读:
    深入理解Linux修改hostname
    Linux开发环境必备十大开发工具
    管理员必备的几个Linux系统监控工具
    Solaris&&QNX® Neutrino®&&OpenVMS&&FreeBSD&&AIX
    ansible来了
    Cobbler系统安装备用链接
    Web安全
    在Eclipse/STS中使用EclEmma进行覆盖率检查
    C#中使用扩展方法
    Winform中Textbox的使用
  • 原文地址:https://www.cnblogs.com/technical-life/p/13121196.html
Copyright © 2011-2022 走看看