Access HttpServletRequest Properties in WebSocket @ServerEndpoint

I need to access the HttpServletRequest properties in order to get the javax.servlet.request.X509 certificate containing an X509Certificate certificate X509Certificate for TLS requests.

From JAX-RS ContainerRequestFilter I can easily extract this from the ContainerRequestContext.getProperty(String property) method, but I cannot find a way to get it from the WebSocket Session or HandshakeRequest from which I can access the HttpSession instance, but not the HttpServletRequest .

Note: this is not a duplicate of Access HttpSession from HttpServletRequest to Web Socket @ServerEndpoint , since I need accesso for HttpServletRequest (or the equivalent for retrieving TLS), not HttpSession .

Since WebSocket is a superset of HTTP, I suppose this should be possible and hope that the Java team thought of a way to access the properties of the servlet, but I really could not find them. Does anyone know if this is possible at all?

+1
source share
1 answer

No hacking:

  • Create a servlet filter at the URL corresponding to the websocket handshake request.
  • In the filter, find the request attribute of interest and place it in the session before continuing the chain.
  • Finally, get it from the session, which, in turn, is only available through a confirmation request.

With hacking:

  • Use reflection to find the ServletRequest field in the acknowledgment request instance.
  • Get the 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; } } 
+2
source

Source: https://habr.com/ru/post/981650/


All Articles