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

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

以上所述是小编给大家介绍的shiro实现单点登录(一个用户同一时刻只能在一个地方登录),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对phpstudy网站的支持!


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3