spring boot创建websocket服务,最近遇到根据客户端ip创建黑名单的需求,但在onOpen或onMessage等方法中一般无法获取ip。整合chatgpt和浏览器搜索结果,摸索出一种方式。
步骤如下:
1、创建过滤器,从HttpRequest对象中获取ip,并存入HttpSession对象.
原理:websocket握手时可以获取到HttpRequest对象,在过滤器中拿到HttpRequest,这样就可以从里面获取到ip并存入HttpSession。
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import zgmencrypt.tool.Verify;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
@javax.servlet.annotation.WebFilter(filterName = "sessionFilter", urlPatterns = "/*")
@Order(1)
@Component
public class WebFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpSession session = req.getSession();
session.setAttribute("user_ip", req.getRemoteHost());//获取ip存入session
if (this.judgeBlack(req.getRemoteHost()) == false) {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
2、创建websocket端点配置类用于配置自定义参数,获取第一步保存的HttpSession,将HttpSession存入HandshakeRequest对象。
原理:HandshakeRequest类用于保存握手消息,存到这个类里就可以到websocket端点的onOpen等方法里拿到了。
package zgmencrypt.config;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
3、配置端点时用注解引入第2步的配置类,然后在onOpen方法里先获取HttpSession,再从HttpSession中获取自定义属性。
ServerEndpoint(value = "/webSocket", configurator = HttpSessionConfigurator.class)
@RestController
@Slf4j
public class WebSocketController {
@OnOpen
public void onOpen(Session session, EndpointConfig config) throws IOException {
// 获取WebSocket握手请求 并获取ip
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
String ip = (String) httpSession.getAttribute("user_ip");
}
}