Spring boot获取websocket客户端ip

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");
    }
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
WebSocketIP地址可以通过以下方式获取和传递: 在WebSocketConfigurator类中,通过modifyHandshake方法将客户端IP地址传递给WebSocket的session。这个类是一个配置类,继承自ServerEndpointConfig.Configurator,并重写了modifyHandshake方法。在这个方法中,通过获取HttpSession对象,将客户端IP地址存储在WebSocket的attributes中,使用了一个常量IP_ADDR作为key来存储IP地址。同时,还将HttpSession中的其他属性也存储在attributes中。\[1\] 在WebSocketConfig类中,使用了Spring BootWebSocket依赖,并配置了一个ServerEndpointExporter的Bean。这个Bean用于将WebSocket的端点暴露给Spring Boot应用程序。\[2\] 在WebFilter类中,定义了一个拦截器,用于获取客户端IP地址,并将其存储在HttpSession中的"ip"属性中。这个拦截器通过@WebFilter注解进行配置,将其应用于所有的URL。\[3\] 综上所述,通过WebSocketConfigurator类、WebSocketConfig类和WebFilter类的配置,可以获取和传递WebSocketIP地址。 #### 引用[.reference_title] - *1* *2* *3* [SpringBoot整合WebSocket获取客户端真实ip)](https://blog.csdn.net/qq_37855749/article/details/118334271)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值