How to check that user has already logged in using Apache Shiro?

一个人想着一个人 提交于 2019-12-04 19:27:20

The Shiro sessions are stored in SessionDAO with sessionId as keys. Without extra effort you cannot access a session by a principal (user name). However, you could extend DefaultSecurityManager and check all active sessions by SessionDAO.getActiveSessions. The following codes could be a simple example (suppose you are not using WebSubject):

public class UniquePrincipalSecurityManager extends org.apache.shiro.mgt.DefaultSecurityManager {

    @Override
    public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {

        String loginPrincipal = (String) token.getPrincipal();
        DefaultSessionManager sm = (DefaultSessionManager) getSessionManager();
        for (Session session : sm.getSessionDAO().getActiveSessions()) {
            SimplePrincipalCollection p = (SimplePrincipalCollection) session
                    .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (p != null && loginPrincipal.equals(p.getPrimaryPrincipal())) {
                throw new AlreadyAuthenticatedException();
            }

        }
        return super.login(subject, token);
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!