security - Websocket(java ee)如何获取当前用户的角色

标签 security jakarta-ee websocket wildfly

我刚刚在我的 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/

相关文章:

iOS 检测模拟位置

security - CSRF陷入困境,withForm {}。invalidToken {}无法正常工作

java - 在 session 中调用对象的方法而不进行类型转换

java - 存储敏感信息

java - websockets api中.sendText()和System.out.println有什么区别

websocket - Clojure WebSocket 应用程序的 nginx prod 设置

html - 黑客通过提交值更改主页如何防止这种情况发生?

azure - 相当于发布管道的 YAML 是什么?

java - 任务监视器 Servlet - 并发问题

java - 为 Spring WebSocket 设置 CSRF