如何在Java中使用HttpSession跟踪登录尝试? [英] How to track login attempts using HttpSession in Java?

查看:137
本文介绍了如何在Java中使用HttpSession跟踪登录尝试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无框架的Web应用程序。我需要使用会话实现一种简单的方法来检查不成功的登录。如果用户尝试使用不正确的用户名/密码组合登录3次,他们将获得20分钟的超时时间,然后再尝试登录。

I have a no-framework web application. I need to implement a simple way to check unsuccessful logins, using sessions. If the user attempts to log in 3 times using incorrect username/password combination, they will be given a 20 minute timeout before they can try logging in again.

目前我只有如果用户成功登录系统,则设置用户会话。但是,似乎我应该在登录失败的情况下获得会话,并以某种方式计算登录尝试。

Currently I only set a user session if the user successfully logs in to the system. However, it seems that I should get a session in case of unsuccessful login also, and count the login attempts somehow.

Login.jsp(简化版):

Login.jsp (simplified version):

<form name="loginForm" method="post" action="CustomerData">
User name:<input type="text" name="userName"/>
Password:<input type="password" name="password"/>
<input type="button" value="submit">

CustomerData.java(简化版):

CustomerData.java (simplified version):

// 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对象实现此功能。

While doing research, I found that there are a lot of built-in security features for various Java frameworks. I also found that using sessions is not the best way to track login attempts, because the user can log-in with different browsers. However, I'm creating this functionality for a simple web project that will never go to any production environment. I would like to know how to implement this functionality using the Java HTTPSession Object.

好的,这是我的完整解决方案,基于我收到的反馈。我发布此内容以防其他人遇到类似问题:

Ok, here is my full solution, based on the feedback I received. I'm posting this in case it might help others with similar issues:

// 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! <br>Not a registered cusomer? Please <a href=\"register.jsp\">register</a>!");
            }
            session.setAttribute("loginCount",loginAttempt);
            url = "/login.jsp";

        }

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);


推荐答案

您可以尝试以下代码

int loginAttempt = (Integer)session.getAttribute("loginCount");

if (loginAttempt > 3 ){
     // Error message/page redirection 
}else{
     session.setAttribute("loginCount",loginAttempt++);
}

这篇关于如何在Java中使用HttpSession跟踪登录尝试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆