您的位置:首页 > 其它

shiro 实现单用户登录,一个用户同一时刻只能在一个地方登录

2016-08-26 11:01 1066 查看
我这里 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 SecurityManager
authc.loginUrl = /login.jsp
authc.successUrl = /web/index.jsp

#cache manager
builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager=org.apache.shiro.web.mgt.DefaultWebSecurityManager
securityManager.cacheManager = $builtInCacheManager
securityManager.sessionManager=$sessionManager

#session 必须配置session,强制退出时,通过将session移除实现
sessionManager=org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO=$sessionDAO

sessionDAO=org.apache.shiro.session.mgt.eis.MemorySessionDAO

# Create ldap realm
ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
#......

# Configure JDBC realm datasource
dataSource = org.postgresql.ds.PGPoolingDataSource
#.......

# Create JDBC realm.
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.userRolesQuery = ......
jdbcRealm.permissionsQuery = ......
jdbcRealm.dataSource = $dataSource

#self realm
localAuthorizingRealm = com.redbudtek.shiro.LocalAuthorizingRealm

securityManager.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信息截图如下:



此时的登录的用户认证已经失效,可以对客户端做出响应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐