登录接口防攻击 03

接着前两篇日志

http://hw1287789687.iteye.com/blog/2215776

http://hw1287789687.iteye.com/blog/2216493

 

我之前遇到过忘记路由器密码的情况,我在192.168.1.1的登录界面尝试可能的密码,希望能够猜中,但是输错3次之后,就必须等待5分钟,我们可以借鉴这种策略.

 

连续3次登录失败,就锁定5分钟(5分钟之内无视登录请求)

解释:

连续登录失败3次,就设置isLocked为true,表示锁定,并设置定时器,任务是5分钟之后设置isLocked为false.

服务器接受到登录请求时,在查询数据库之前先判断是否锁定,若isLocked为true,则不用查询数据库,直接返回登录失败.若isLocked为false,则正常查询数据库.

被锁定之后,必须等待5分钟,若锁定之后登录,则定时器重新计时.

比如我等待了2分钟,还要等3分钟,我就又可以登录了.但是还需要等3分钟的时候我还去登录,那么定时器从此刻开始计时,即我又要等待5分钟.

在锁定期间,接收登录请求不会访问数据库.

 

具体实现:

(a)spring 的aop

在登录校验方法处添加aop切面,类型是around

上代码:

Java代码   收藏代码
  1. package com.shop.jn.aop;  
  2.   
  3. import java.util.Timer;  
  4.   
  5. import org.apache.log4j.Logger;  
  6. import org.aspectj.lang.ProceedingJoinPoint;  
  7.   
  8. import com.common.entity.user.interf.GenericUser;  
  9. import com.common.util.LoginUtil;  
  10. import com.common.util.SystemHWUtil;  
  11. import com.opensymphony.xwork2.Action;  
  12. import com.shop.jn.common.MyTask;  
  13. import com.shop.jn.listener.UploadedFilesServletContextListener;  
  14.   
  15. public class LoginTimesAop {  
  16.     private Logger logger = Logger.getLogger(this.getClass());  
  17.     private int timesFail = 0;  
  18.     private Timer timer = new Timer();  
  19.     private MyTask task = null;  
  20.     /*** 
  21.      * 因连续登录失败的次数达到上限,而锁定:规定时间内无法登录 
  22.      */  
  23.     private boolean isLocked = false;  
  24.     private String classSimpleName = this.getClass().getSimpleName();  
  25.   
  26.     public LoginTimesAop() {  
  27.         super();  
  28.         logger.info("aop:constructor.");  
  29.     }  
  30.   
  31.     public void before3(GenericUser user) {  
  32.         System.out.println("user:" + user.getUsername());  
  33.         logger.info("aop:before3");  
  34.     }  
  35.   
  36.     // public void monitor(String username, String passwd) {  
  37.     // timesFail++;  
  38.     // logger.info("aop:-------------------------------------");  
  39.     // logger.info("username:" + username + " , password:" + passwd);  
  40.     // System.out.println("username:" + username + " , password:" + passwd);  
  41.     // System.out.println("times of fail:" + timesFail+" times.");  
  42.     // }  
  43.   
  44.     // ,ProceedingJoinPoint call  
  45.     public Object around(ProceedingJoinPoint call, GenericUser user)  
  46.             throws Throwable {  
  47.         if(!UploadedFilesServletContextListener.isLimitLoginFailedThreeTimes){  
  48.             return call.proceed();  
  49.         }  
  50.         String aop_info = "aop[" + classSimpleName + "]:";  
  51.         // logger.info(aop_info + "This is around method.");  
  52.         // logger.info("username:" + user.getUsername() + " ,password:"  
  53.         // + user.getPassword());  
  54.   
  55.         Object[] obj;  
  56.         if (!isLocked()) {// 没有锁定  
  57.             //com.common.service.impl.SUserService  Object[] login(String username,String passwd)  
  58.             obj = (Object[]) call.proceed();//负责登录校验的,真正干活的.  
  59.             int resultCode = (Integer) obj[0];  
  60.             if (resultCode == LoginUtil.LOGIN_RESULT_SUCCESS) {  
  61.                 timesFail = 0;  
  62.             } else {// 登录失败  
  63.                 timesFail++;  
  64.                 logger.info(aop_info + "times of fail:" + timesFail + " times.");  
  65.             }  
  66.         } else {  
  67.             logger.info("账号已被锁定");  
  68.             obj = new Object[2];  
  69.         }  
  70.         // 连续登录失败超过3次  
  71.         if (UploadedFilesServletContextListener.isLimitLoginFailedThreeTimes/* 
  72.                                                                              * 是否限定连续登录失败三次就锁定 
  73.                                                                              */  
  74.                 && timesFail >= LoginUtil.MAX_LOGIN_FAIL_TIMES) {  
  75.             // ValueStack stack = actionContext.getValueStack();  
  76.             // stack.set("MESSAGE_IS_LOGIN", "You have failed " + timesFail  
  77.             // + " times.");  
  78.   
  79.             if (isLocked()) {// over three times and is still locked,meanwhile use  
  80.                             // try to log in  
  81.                 if (task != null) {  
  82.                     logger.info(aop_info + " cancel task.");  
  83.                     task.cancel();  
  84.                     task = null;  
  85.                 }  
  86.             } else {// first into this if clause(if (timesFail >=  
  87.                     // LoginUtil.MAX_LOGIN_FAIL_TIMES ))  
  88.                 task = null;  
  89.             }  
  90.             if (timer == null) {  
  91.                 timer = new Timer();  
  92.             }  
  93.   
  94.             if (task == null) {  
  95.                 task = new MyTask(this);  
  96.             }  
  97.             logger.info(aop_info + "start task....");  
  98.             timer.schedule(task, LoginUtil.MILLISECONDS_WAIT_WHEN_FAIL);  
  99.             setLocked(true);  
  100.             // Object[] results = new Object[2];  
  101.             obj[0] = LoginUtil.LOGIN_RESULT_OVER_TIMES;/* 
  102.                                                          * You have failed three 
  103.                                                          * times. 
  104.                                                          */  
  105.             // return results;// not success  
  106.             logger.info(SystemHWUtil.DIVIDING_LINE);  
  107.         }  
  108.         return obj;  
  109.     }  
  110.   
  111.     // public void before() {  
  112.     // logger.info("aop:This is before method:user try to log in......");  
  113.     // System.out.println("aop:before");  
  114.     // }  
  115.   
  116.     public void afterReturning(Object retVal) {  
  117.         logger.info("aop:return code:" + (String) retVal);  
  118.         if (retVal == null || !retVal.equals(Action.SUCCESS)) {  
  119.             logger.warn("aop:login failed!");  
  120.         }  
  121.     }  
  122.   
  123.     // public void before2(User user){  
  124.     // logger.info("aop:This is before2 method:user try to log in......");  
  125.     // logger.info("username:" + user.getUsername() + " , password:" +  
  126.     // user.getPassword());  
  127.     // }  
  128.   
  129.     public int getTimesFail() {  
  130.         return timesFail;  
  131.     }  
  132.   
  133.     public void setTimesFail(int timesFail) {  
  134.         this.timesFail = timesFail;  
  135.     }  
  136.   
  137.     public synchronized boolean isLocked() {  
  138.         return isLocked;  
  139.     }  
  140.   
  141.     public synchronized void  setLocked(boolean isLocked) {  
  142.         this.isLocked = isLocked;  
  143.     }  
  144.   
  145. }  

 定时器执行的任务

Java代码   收藏代码
  1. public class MyTask extends java.util.TimerTask{  
  2.     private LoginTimesAop loginTime;  
  3.       
  4.     public MyTask(LoginTimesAop loginTime) {  
  5.         super();  
  6.         this.loginTime=loginTime;  
  7.     }  
  8.   
  9.     @Override  
  10.     public void run() {  
  11.         loginTime.setTimesFail(0);  
  12.         loginTime.setLocked(false);  
  13.     }  
  14. }  

 aop配置:

Xml代码   收藏代码
  1. <aop:pointcut id="userServicePointcut"  
  2.             expression="execution(* com.common.service.impl.SUserService.login(..)) and args(..,user2)" />  
  3.         <aop:aspect id="myAspect" ref="loginTimesAop">  
  4.             <aop:before method="before3" arg-names="user2" pointcut-ref="userServicePointcut"   
  5.                 />  
  6.             <aop:around pointcut-ref="userServicePointcut" method="around"  
  7.                 arg-names="user2" />  
  8.         </aop:aspect>  

 

(b)spring MVC中的拦截器,需继承org.springframework.web.servlet.HandlerInterceptor

关于拦截器参考:spring mvc xml配置拦截器

拦截器的demo

Java代码   收藏代码
  1. import javax.servlet.http.HttpServletRequest;  
  2. import javax.servlet.http.HttpServletResponse;  
  3.   
  4. import org.springframework.web.servlet.ModelAndView;  
  5. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;  
  6.   
  7. public class HandlerInterceptor1 extends HandlerInterceptorAdapter {  
  8.     @Override    
  9.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {    
  10.         System.out.println("===========HandlerInterceptor1 preHandle");    
  11.         return true;    
  12.     }    
  13.     @Override    
  14.     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {    
  15.         System.out.println("===========HandlerInterceptor1 postHandle");    
  16.     }    
  17.     @Override    
  18.     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {    
  19.         System.out.println("===========HandlerInterceptor1 afterCompletion");    
  20.     }    
  21. }  

 

参考:http://hw1287789687.iteye.com/blog/2215776

http://hw1287789687.iteye.com/blog/2216493

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值