SessionAuthHandshakeInterceptor.java 1.54 KB
package com.huaheng.pc.stompwebsocket;

import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.pc.stompwebsocket.service.StompWebSocketServiceImpl;
import com.huaheng.pc.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.Map;

@Component("sessionAuthHandshakeInterceptor")
public class SessionAuthHandshakeInterceptor implements HandshakeInterceptor {
    @Autowired
    @Lazy
    private StompWebSocketServiceImpl stompWebSocketService;
    @Override
    public boolean beforeHandshake (ServerHttpRequest Request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                    Map<String, Object> attributes) throws Exception {

        User user = ShiroUtils.getUser();
        if (user == null) {
            return false;
        }
//        attributes.put("user ", user.getLoginName());
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        User user = ShiroUtils.getUser();
        stompWebSocketService.sendOfflineMessageToUser(user.getLoginName());
    }


}