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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值