Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access UserAgent in Websocket session?

Using the Tyrus reference implementation of Java's "JSR 356 - Java API for WebSocket", I cannot find a way to access the HTTP connection that was used for the Websocket upgrades. Thus, I cannot access the HTTP headers that the browser sent.

Is there a way to read the HTTP UserAgent header?

Casting a "Session" object to "TyrusSession" or similar would be acceptable, I have to do it to get the Remote Address anyway. Sending the UserAgent again as a message inside the Websocket connection would be my fallback solution.

like image 549
lathspell Avatar asked Dec 12 '25 23:12

lathspell


1 Answers

WARNING: ServerEndpointConfig is shared among all endpoint instances and multiple upgrade requests can be done concurrently! See comments!

The endpoint gets a configurator:

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/foo", configurator = MyServerEndpointConfigurator.class)
public class MyEndpoint {

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) throws Exception {
        String ip = ((TyrusSession) session).getRemoteAddr();
        String userAgent = (String) endpointConfig.getUserProperties().get("user-agent");
        ...
   }
}

The configurator looks like this:

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public class MyServerEndpointConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        if (request.getHeaders().containsKey("user-agent")) {
            sec.getUserProperties().put("user-agent", request.getHeaders().get("user-agent").get(0)); // lower-case!
        }
    }
}
like image 173
lathspell Avatar answered Dec 14 '25 20:12

lathspell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!