Accessing HttpServletRequest properties within a WebSocket @ServerEndpoint

前端 未结 1 2068
滥情空心
滥情空心 2020-12-11 12:43

I need to access the HttpServletRequest properties to get the javax.servlet.request.X509Certificate which contains the X509Certificate arr

相关标签:
1条回答
  • 2020-12-11 13:15

    Without hacking:

    1. Create servlet filter on URL pattern matching websocket handshake request.
    2. In filter, get request attribute of interest and put it in session before continuing chain.
    3. Finally get it from the session which is in turn just available via handshake request.

    With hacking:

    1. Use reflection to find ServletRequest field in handshake request instance.
    2. Get its javax.servlet.request.X509Certificate attribute.

      In other words:

      public class ServletAwareConfigurator extends Configurator {
      
          @Override
          public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
              ServletRequest servletRequest = getField(request, ServletRequest.class);
              X509Certificate[] certificates = (X509Certificate[]) servletRequest.getAttribute("javax.servlet.request.X509Certificate");
              // ...
          }
      
          private static <I, F> F getField(I instance, Class<F> fieldType) {
              try {
                  for (Class<?> type = instance.getClass(); type != Object.class; type = type.getSuperclass()) {
                      for (Field field : type.getDeclaredFields()) {
                          if (fieldType.isAssignableFrom(field.getType())) {
                              field.setAccessible(true);
                              return (F) field.get(instance);
                          }
                      }
                  }
              } catch (Exception e) {
                  // Handle?
              }
      
              return null;
          }
      
      }
      
    0 讨论(0)
提交回复
热议问题