我有一个无框架的Web应用程序。我需要使用会话来实现一种检查不成功登录的简单方法。如果用户尝试使用不正确的用户名/密码组合登录3次,则会给他们20分钟的超时时间,然后才能再次尝试登录。
当前,只有在用户成功登录系统后,我才设置用户会话。但是,似乎我也应该在未成功登录的情况下进行会话,并以某种方式计算登录尝试次数。
Login.jsp(简体版):
User name:
Password:
CustomerData.java(简化版):
// See if customer is a valid user
String selectQuery = "Select firstName,lastName,email from customer where userName='"+userName+"' and password='"+password+"'";
selectResult = statement.executeQuery(selectQuery);
if(selectResult.next())
{
// We got a valid user, let's log them in
....
HttpSession session = request.getSession(true);
session.setAttribute("customer", customer);
}
else
{
// this is where I need to get the session id (??),
// count the unsuccessful login attempts somehow,
//and give them a 20 minutes timeout before they can try logging in again.
request.setAttribute("message","Invalid username or password. Please try again!");
}
在进行研究时,我发现各种Java框架都有很多内置的安全功能。我还发现使用会话不是跟踪登录尝试的最佳方法,因为用户可以使用不同的浏览器登录。但是,我正在为一个永远不会进入任何生产环境的简单Web项目创建此功能。我想知道如何使用Java
HTTPSession对象实现此功能。
好的,这是我收到的反馈的完整解决方案。我发布此信息是为了防止其他人遇到类似问题:
// See if customer is a valid user
String selectQuery = "Select firstName,lastName,email from customer where userName='"+userName+"' and password='"+password+"'";
selectResult = statement.executeQuery(selectQuery);
if(selectResult.next())
{
// We got a valid user, let's log them in
Customer customer = new Customer();
customer.setFirstName(selectResult.getString("firstName"));
customer.setLastName(selectResult.getString("lastName"));
customer.setEmail(selectResult.getString("email"));
customer.setUserName(userName);
customer.setPassword(password);
// establish a user session
session.setAttribute("customer", customer);
session.setAttribute("firstName", customer.getFristName());
url = "/index.jsp";
selectResult.close();
}
else
{
int loginAttempt;
if (session.getAttribute("loginCount") == null)
{
session.setAttribute("loginCount", 0);
loginAttempt = 0;
}
else
{
loginAttempt = (Integer) session.getAttribute("loginCount");
}
//this is 3 attempt counting from 0,1,2
if (loginAttempt >= 2 )
{
long lastAccessedTime = session.getLastAccessedTime();
date = new Date();
long currentTime = date.getTime();
long timeDiff = currentTime - lastAccessedTime;
// 20 minutes in milliseconds
if (timeDiff >= 1200000)
{
//invalidate user session, so they can try again
session.invalidate();
}
else
{
// Error message
session.setAttribute("message","You have exceeded the 3 failed login attempt. Please try loggin in in 20 minutes, or call our customer service center at 1-800 555-1212.");
}
}
else
{
loginAttempt++;
int allowLogin = 3-loginAttempt;
session.setAttribute("message","loginAttempt= "+loginAttempt+". Invalid username or password. You have "+allowLogin+" attempts remaining. Please try again!
Not a registered cusomer? Please register!");
}
session.setAttribute("loginCount",loginAttempt);
url = "/login.jsp";
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);