当前位置:   article > 正文

Spring boot获取websocket客户端ip_springboot 获取websocket客户端信息

springboot 获取websocket客户端信息

spring boot创建websocket服务,最近遇到根据客户端ip创建黑名单的需求,但在onOpen或onMessage等方法中一般无法获取ip。整合chatgpt和浏览器搜索结果,摸索出一种方式。

步骤如下:

1、创建过滤器,从HttpRequest对象中获取ip,并存入HttpSession对象.

原理:websocket握手时可以获取到HttpRequest对象,在过滤器中拿到HttpRequest,这样就可以从里面获取到ip并存入HttpSession。

  1. import com.sun.org.apache.xpath.internal.operations.Bool;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.stereotype.Component;
  5. import zgmencrypt.tool.Verify;
  6. import javax.servlet.*;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpSession;
  9. import javax.websocket.Session;
  10. import java.io.IOException;
  11. @javax.servlet.annotation.WebFilter(filterName = "sessionFilter", urlPatterns = "/*")
  12. @Order(1)
  13. @Component
  14. public class WebFilter implements Filter {
  15. @Override
  16. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  17. HttpServletRequest req = (HttpServletRequest) servletRequest;
  18. HttpSession session = req.getSession();
  19. session.setAttribute("user_ip", req.getRemoteHost());//获取ip存入session
  20. if (this.judgeBlack(req.getRemoteHost()) == false) {
  21. filterChain.doFilter(servletRequest, servletResponse);
  22. }
  23. }
  24. }

2、创建websocket端点配置类用于配置自定义参数,获取第一步保存的HttpSession,将HttpSession存入HandshakeRequest对象。

原理:HandshakeRequest类用于保存握手消息,存到这个类里就可以到websocket端点的onOpen等方法里拿到了。

  1. package zgmencrypt.config;
  2. import javax.servlet.http.HttpSession;
  3. import javax.websocket.HandshakeResponse;
  4. import javax.websocket.server.HandshakeRequest;
  5. import javax.websocket.server.ServerEndpointConfig;
  6. public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator {
  7. @Override
  8. public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
  9. HttpSession httpSession = (HttpSession) request.getHttpSession();
  10. config.getUserProperties().put(HttpSession.class.getName(), httpSession);
  11. }
  12. }

3、配置端点时用注解引入第2步的配置类,然后在onOpen方法里先获取HttpSession,再从HttpSession中获取自定义属性。

  1. ServerEndpoint(value = "/webSocket", configurator = HttpSessionConfigurator.class)
  2. @RestController
  3. @Slf4j
  4. public class WebSocketController {
  5. @OnOpen
  6. public void onOpen(Session session, EndpointConfig config) throws IOException {
  7. // 获取WebSocket握手请求 并获取ip
  8. HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
  9. String ip = (String) httpSession.getAttribute("user_ip");
  10. }
  11. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/405770
推荐阅读
相关标签
  

闽ICP备14008679号