Websocket (java ee) how to get role of current user

1.5k views Asked by At

I just added a Websocket endpoint to my java ee jax-rs application. Within Jax-Rs endpoints i can access the role of the user via SecurityContext.

But within websocket i can't inject context stuff. So how to know the role of the user that tries to open a websocket session?

1

There are 1 answers

1
MSD On BEST ANSWER

For this you will have to modify the Websocket handshake. You can do this as below:

1) Modify you websocket endpoint to use custom configurator

@ServerEndpoint(value = "/someWSEndpoint", configurator = SomeCustomConfigurationClass.class)
public class SomeWSService {
...
}

2) Modify WS Handshake similar to

public class SomeCustomConfigurationClass extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config, 
                                HandshakeRequest request, 
                                HandshakeResponse response) {

    config.getUserProperties().put("UserPrincipal",request.getUserPrincipal());
    config.getUserProperties().put("userInRole", request.isUserInRole("someRole"));     
    }
}

3) Now you can access this in you ws endpoint class as

@OnOpen
public void onOpen(final Session session, EndpointConfig config) {
        Principal userPrincipal = (Principal) config.getUserProperties().get("UserPrincipal");
        Boolean userInRole =  (Boolean) config.getUserProperties().get("userInRole");
        //do what ever you like with it
}