使特定用户的会话无效 [英] Invalidate Session of a specific user

查看:116
本文介绍了使特定用户的会话无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此对于我的Web应用程序,如果我删除当前登录的用户,并且想要使他/她的会话无效.这样一来,只要他/她刷新页面或导航,它们就不再登录.我现在的方式是,如果一个用户成功登录,我会将用户对象存储在我的SessionScoped bean中,并存储HttpSessionApplication Map.下面是我的代码

So for my webapp, if I remove a user that is currently logged in, and I want to invalidate his/her session. So that as soon as he/she refresh the page or navigate, they are no longer log in. The way I have now is that if a User logged in successfully, I will store the user object in my SessionScoped bean, and store the HttpSession to the Application Map. Below is my code

这是我的SessionScoped bean

@PostConstruct
public void init() {
    User user = UserDAO.findById(userId, password);
    Map<String, Object> appMap = FacesContext.getCurrentInstance().
             getExternalContext().getApplicationMap();
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().
             getExternalContext().getSession(false);
    appMap.put(userId, session);
}

这是正确的方法吗?如果是这样,我该如何清理我的应用程序映射?

Is this a correct approach? If so, how do I clean up my application map?

推荐答案

这是正确的方法吗?

基本上有两种方法.

  1. 通过用户ID作为密钥将HttpSession句柄存储在应用程序范围中,以便您可以获取它的句柄并使它无效.这可能适用于在单个服务器上运行的小型Web应用程序,但可能不适用于在服务器群集上运行的Web应用程序,具体取决于其配置.

  1. Store the HttpSession handle in the application scope by the user ID as key so that you can get a handle of it and invalidate it. This may work for a small web application running on a single server, but may not work on a web application running on a cluster of servers, depending on its configuration.

我只会将其存储在应用程序范围的另一个映射中,而不是像您那样直接存储在应用程序范围中,以便您可以更轻松地获得所有用户的概况,并可以保证例如,任意用户ID不会与现有应用程序范围的托管Bean名称冲突.

I would only store it in another map in the application scope, not directly in the application scope like as you did, so that you can easier get an overview of all users and that you can guarantee that an arbitrary user ID won't clash with an existing application scoped managed bean name, for example.

向与用户关联的某些数据库表中添加一个新的布尔值/位列,该列在每个HTTP请求中都进行检查.如果管理员将其设置为true,则与请求关联的会话将无效,并且数据库中的值将被重新设置为false.

Add a new boolean/bit column to some DB table associated with the user which is checked on every HTTP request. If the admin sets it to true, then the session associated with the request will be invalidated and the value in the DB will be set back to false.


如何清理我的应用程序映射?

您可以使用 HttpSessionListener#sessionDestroyed() .例如

You could use HttpSessionListener#sessionDestroyed() for this. E.g.

public void sessionDestroyed(HttpSessionEvent event) {
    User user = (User) event.getSession().getAttribute("user");
    if (user != null) {
        Map<User, HttpSession> logins = (Map<User, HttpSession>) event.getSession().getServletContext().getAttribute("logins");
        logins.remove(user);
    }
}

这篇关于使特定用户的会话无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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