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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With