Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 522
dermoritz Avatar asked Mar 15 '23 19:03

dermoritz


1 Answers

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
}
like image 129
MSD Avatar answered Mar 25 '23 05:03

MSD