如何阻止或限制多次调用动作Struts(抓取器)

时间:2016-06-14 20:23:40

标签: java spring struts2

我有一个Struts2 / Spring应用程序,我想知道如何阻止"抓取器"。

在我的服务器上,我检测到一些抓取器多次调用相同的动作struts,结果是我的服务器在抓取过程中变得太慢而数据库有多次点击。

如何停止对相同操作struts的多次调用并最小化数据库命中?

例如,抓取器以相同的动作调用超过40次/分钟。

从安全的角度来看,我认为我应该使用缓存来存储IP地址和电话号码,如果超过限制就阻止ip。

但我不知道该怎么做。

如果你已经这样做了,请告诉我如何实施解决方案?

1 个答案:

答案 0 :(得分:0)

如果您正在使用struts2和spring,那么您应该查看Spring Security限制用户尝试的功能。如果用户尝试失败3次,则应阻止用户并且无法访问页面,如果尝试小于3,我们应该重置计数器。此外,每次登录尝试都应使用csrf令牌。

Spring Security

查看this实施情况。

主要文件是 LimitLoginAuthenticationProvider.java

package com.mkyong.web.handler;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import com.mkyong.users.dao.UserDetailsDao;
import com.mkyong.users.model.UserAttempts;

@Component("authenticationProvider")
public class LimitLoginAuthenticationProvider extends DaoAuthenticationProvider {

@Autowired
UserDetailsDao userDetailsDao;

@Autowired
@Qualifier("userDetailsService")
@Override
public void setUserDetailsService(UserDetailsService userDetailsService) {
    super.setUserDetailsService(userDetailsService);
}

@Override
public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {

  try {

    Authentication auth = super.authenticate(authentication);

    //if reach here, means login success, else an exception will be thrown
    //reset the user_attempts
    userDetailsDao.resetFailAttempts(authentication.getName());

    return auth;

  } catch (BadCredentialsException e) { 

    //invalid login, update to user_attempts
    userDetailsDao.updateFailAttempts(authentication.getName());
    throw e;

  } catch (LockedException e){

    //this user is locked!
    String error = "";
    UserAttempts userAttempts = 
                userDetailsDao.getUserAttempts(authentication.getName());

           if(userAttempts!=null){
        Date lastAttempts = userAttempts.getLastModified();
        error = "User account is locked! <br><br>Username : " 
                       + authentication.getName() + "<br>Last Attempts : " + lastAttempts;
    }else{
        error = e.getMessage();
    }

  throw new LockedException(error);
}

}

}

Struts2的

通过在struts2中实现拦截器也可以做到这一点。

public class MyAction implements SessionAware {
private Map<String, Object> session;

@Override
public String execute() {
    if (session.containsKey("loginAttempts")) {
        Integer loginAttempts = (Integer) session.get("loginAttempts");
        if (loginAttempts > 3) {
            //block user
        } else {
            session.put("loginAttempts", loginAttempts+1);
        }
    }
}

@Override
public void setSession(Map<String, Object> session) {
    this.session = session;
}
}

使用拦截器

public String intercept (ActionInvocation invocation) throws Exception {
// Get the action context from the invocation so we can access the
// HttpServletRequest and HttpSession objects.
final ActionContext context = invocation.getInvocationContext ();
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
HttpSession session =  request.getSession (true);

// Is there a "user" object stored in the user's HttpSession?
Object user = session.getAttribute (USER_HANDLE);
if (user == null) {
    // The user has not logged in yet.

    // Is the user attempting to log in right now?
    String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
    if (! StringUtils.isBlank (loginAttempt) ) { // The user is attempting to log in.

        // Process the user's login attempt.
        if (processLoginAttempt (request, session) ) {
            // The login succeeded send them the login-success page.
            return "login-success";
        } else {
            // The login failed. Set an error if we can on the action.
            Object action = invocation.getAction ();
            if (action instanceof ValidationAware) {
                ((ValidationAware) action).addActionError ("Username or password incorrect.");
            }
        }
    }

    // Either the login attempt failed or the user hasn't tried to login yet, 
    // and we need to send the login form.
    return "login";
} else {
    return invocation.invoke ();
}
}

您可以在3次尝试失败后使用Recaptcha或重置密码。

从安全角度来看,你必须多做一点。例如,使用缓存来存储IP地址和登录尝试,如果用完了所有登录尝试,则阻止ip。使用Spring和Guavas自动过期缓存,可以使用expireAfterWrite(10, TimeUnit.MINUTES)轻松实现。

如果你只想存储/缓存ipaddress并计算为键值对Spring Radis在spring框架中也是不错的选择。