【问题标题】:Websocket Pathparam ValidationWebsocket 路径参数验证
【发布时间】:2018-11-21 04:30:03
【问题描述】:

我尝试在服务器端应用 websockets 以接收来自不同客户端的信息 websocket Endpoint 使用路径参数来识别特定的客户端。

ws://192.168.1.100:8080/listener/device_00001

而终点类是:

@ServerEndpoint(
   value = "/listener/{deviceid}",
   configurator = WsConfig.class,
   subprotocols = {"abcProtocolv1", "abcProtocolv2"}
)
public class WsServer {

   @OnOpen
   public void onOpen(final Session session, @PathParam("deviceid") final String id) {
      //some handling method
   }

   @OnClose
   //some code here

   @OnMessage
   //some code here

}

在这一步之前代码运行良好,我可以接收来自不同客户端的消息并根据路径参数识别设备。

但是,如果设备 ID 无效,我想发送 404 响应以使升级握手失败。 404 响应应该在@OnOpen 之前发送,我检查了配置器,只包含五个函数:

  • 获取端点实例
  • getNegotiatedSubprotocol
  • getNegotiatedExtensions
  • checkOrigin
  • 修改握手

所有函数似乎都无法在升级握手之前处理验证,但我找不到任何通用方法。

我也应该申请@WebFilter 吗?或者@ServerEndPoint 有什么通用的方法吗?

【问题讨论】:

    标签: java websocket


    【解决方案1】:

    我最终尝试在modifyHandshake 中处理验证,但这不应该是一种常见的方法。

    modifyHandshake 中,@PathParam 变量可以在request.getParameterMap() 中找到。

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        String deviceId = request.getParameterMap().get("deviceid").get(0);
        if (isDeviceValid(deviceId)) {
           //Some code here and 101 is kept 
        } else {
           //Use java reflection to modify the http status and then clear the header 
           //The reflection code is depended on your Http Handler type
           response.getHeaders().clear()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多