使用shiro与websocket做单一登陆

shiro配置就不说了,网上多的很,websocket的配置可以看我另一篇文章:https://blog.csdn.net/qq_37838223/article/details/80419325


    org.springframework.boot
    spring-boot-starter-websocket


    com.github.theborakompanioni
    thymeleaf-extras-shiro
    1.2.1

private final Logger logger = LoggerFactory.getLogger(AuthRealm.class);
@Autowired
private SimpMessagingTemplate messagingTemplate;

//认证,登录
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken tokens) throws AuthenticationException {
    UsernamePasswordToken token=(UsernamePasswordToken)tokens;//获取用户输入的token
    String username=token.getUsername();
    String password=new String(token.getPassword());
    User user=new User();
    user.setUsername(username);
    user.setPassword("123456");
    SessionsSecurityManager securityManager = (SessionsSecurityManager) SecurityUtils.getSecurityManager();
    DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager();
    Collection sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
        for (Session session : sessions) {
            User users = (User) (session.getAttribute("USER_IN_SESSION"));
            if (users != null) {
                if (username.equals(users.getUsername())&&password.equals(users.getPassword())) {
                    if(SecurityUtils.getSubject().getSession().getId().equals(session.getId())){
                        break;
                    }else {
                        logger.debug(username + "已登录,移除以保存的session");
                        sessionManager.getSessionDAO().delete(session);
                        messagingTemplate.convertAndSendToUser(username, "/queue/message", new WiselyResponse("该账号已在其他机器登陆!"));
                    }
                }
            }
        }
    SimpleAuthenticationInfo ai=new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    return ai;
}
借鉴的博客:https://www.cnblogs.com/zhanying999666/p/8392592.html

你可能感兴趣的:(shiro)