shiro配置就不说了,网上多的很,websocket的配置可以看我另一篇文章:https://blog.csdn.net/qq_37838223/article/details/80419325
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>1.2.1</version> </dependency>
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<Session> 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; }
<script th:inline="javascript"> // var session=[[session.USER_IN_SESSION]]; var user=[[${session.USER_IN_SESSION.username}]]; var socket = new SockJS('/endpointWisely'); //1 stompClient = Stomp.over(socket);//2 stompClient.connect({ name: user }, function(frame) {//3 stompClient.subscribe('/user/queue/message', function (response) { var returnData = JSON.parse(response.body); showResponse("你接收到的消息为:" + returnData.responseMessage); }); }); function disconnect() { if (stompClient != null) { stompClient.disconnect(); } } function showResponse(message) { alert(message) } </script>借鉴的博客:https://www.cnblogs.com/zhanying999666/p/8392592.html