我刚刚在我的 java ee jax-rs 应用程序中添加了一个 Websocket 端点。在 Jax-Rs 端点中,我可以通过 SecurityContext 访问用户的角色。
但是在 websocket 中我不能注入(inject)上下文的东西。那么如何知道尝试打开 websocket session 的用户的角色呢?
最佳答案
为此,您必须修改 Websocket 握手。您可以按以下方式执行此操作:
1) 修改您的 websocket 端点以使用自定义配置器
@ServerEndpoint(value = "/someWSEndpoint", configurator = SomeCustomConfigurationClass.class)
public class SomeWSService {
...
}
2) 修改 WS Handshake 类似于
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)现在您可以在 ws 端点类中访问它
@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
}
关于security - Websocket(java ee)如何获取当前用户的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729287/