你的位置:首页 > Java教程

[Java教程]shiro 实现单用户登录,一个用户同一时刻只能在一个地方登录


我这里 shiro 并没有集成 springMVC,直接使用 ini 配置文件。

shiro.ini

[main]# Objects and their properties are defined here,# Such as the securityManager, Realms and anything# else needed to build the SecurityManagerauthc.loginUrl = /login.jspauthc.successUrl = /web/index.jsp#cache managerbuiltInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManagersecurityManager=org.apache.shiro.web.mgt.DefaultWebSecurityManagersecurityManager.cacheManager = $builtInCacheManagersecurityManager.sessionManager=$sessionManager#session 必须配置session,强制退出时,通过将session移除实现sessionManager=org.apache.shiro.web.session.mgt.DefaultWebSessionManagersessionManager.sessionDAO=$sessionDAOsessionDAO=org.apache.shiro.session.mgt.eis.MemorySessionDAO# Create ldap realmldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm#......# Configure JDBC realm datasourcedataSource = org.postgresql.ds.PGPoolingDataSource#.......# Create JDBC realm.jdbcRealm.permissionsLookupEnabled = truejdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealmjdbcRealm.userRolesQuery = ......jdbcRealm.permissionsQuery = ......jdbcRealm.dataSource = $dataSource#self realmlocalAuthorizingRealm = com.redbudtek.shiro.LocalAuthorizingRealmsecurityManager.realms = $ldapRealm, $localAuthorizingRealm

 

在 LocalAuthorizingRealm 中,用户登录进行认证之前,先将该用户的其他session移除:

@Override  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {    String userName = (String)authenticationToken.getPrincipal();    //处理session    DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();    DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();    Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表    for(Session session:sessions){      //清除该用户以前登录时保存的session      if(userName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {        sessionManager.getSessionDAO().delete(session);      }    }    String pwd = null;    return new SimpleAuthenticationInfo(userName,pwd,getName());  }

 

当session删除之后,必须有客户端与服务器端的交互,shiro才能进行认证判断。在与服务器交互时,subject信息截图如下:

此时的登录的用户认证已经失效,可以对客户端做出响应。