如何防止在java中的不同设备上使用相同凭据进行多次登录

时间:2014-07-31 07:04:11

标签: java session servlets

我要求:我需要阻止在不同设备上使用相同凭据进行多次登录,即登出以前的登录用户并允许新用户登录。

让我们说user_A已经登录,然后user_B尝试使用相同的user_A凭据登录应用程序,然后注销user_A并允许user_B登录。我尝试使用servletsession,但无法解决。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您需要有一个应用范围的概念。

当用户登录时,只需将他注册为在此应用程序范围上下文中登录(例如,如果您使用的是jsf / cdi,则将其存储在@ApplicationScoped@Singleton bean中)< / p>

此示例假定您正在定义自己的上下文。

//Application scoped.
//You need also more or less make it singleton
public enum MyApplication{
  CURRENT_APPLICATION;

  public void onLogin(MyUser user, HttpSession session){}
  public MyUser getCurrentUser(HttpSession session) {}
  public boolean isLoggedIn(MyUser user){} //logged in on any session
  public boolean isLoggedIn(MyUser user, HttpSession session){} //logged in on this session
  public void logoutUser(MyUser user){} //logs out the user in any session
}

public class MyServlet extends HttpServlet{
  //somewher in do get or post
  private void login(String username, String password) {
    MyUser user = findUser(username, password);
    boolean loggedInAnotherSession = MyApplication.CURRENT_APPLICATION.isLoggedInUser(user);
    //logout the user from the other session or something like that
    boolean loggedInOnThisSession = MyApplication.CURRENT_APPLICATION.isLoggedInUser(user, getSession()); //session from http request
    //logout the user if the he is loggedin in a different session other than this
    if(!loggedInAnotherSession || !loggedInOnThisSession){
      //user is either logged in a different session or not logged in at all.
      //login the user
      MyApplication.CURRENT_APPLICATION.onLogin(user, getSession());
    }
  }
}

答案 1 :(得分:0)

您需要使用会话属性并检查属性是否为空。如果属性不为空,则将其替换为新的用户对象。

User currentUser=(User)request.getSession().getAttribute("loggedUser");

if(currentUser!=null)
request.getSession().setAttribute("loggedUser",currentUser);

else
request.getSession(true).setAttribute("loggedUser",currentUser);

答案 2 :(得分:0)

不是Java,可能过于简化,但是嘿......它适用于Web2Py:

只有成功登录后,我才会在MySQL DB的auth_membership表中编写SessionID(response.session_id)。 在登录页面(索引页面)上,我检查当前的response.session_id是否等于来自DB的SessionID。 如果是这样 - 一切都很好。 如果不是 - (“较旧的”,第一个)用户被礼貌地注销。

上述工作自从每次登录后都会创建一个新的response.session_id并存储在数据库中。 检查仅在登录页面上进行(在我的应用程序中是最重要的一个,启动许多其他功能),因此上面没有太多的数据库命中。 以上内容不依赖于用户注销。 没有涉及IP地址(其他人提到过,有自己的问题) 它一次只允许一个用户登录,并注销“较旧”的用户。

希望它有所帮助 NeoToren