【问题标题】:Websocket (java ee) how to get role of current userWebsocket(java ee)如何获取当前用户的角色
【发布时间】:2015-06-09 10:20:42
【问题描述】:

我刚刚向我的 java ee jax-rs 应用程序添加了一个 Websocket 端点。在 Jax-Rs 端点中,我可以通过 SecurityContext 访问用户的角色。

但在 websocket 中我无法注入上下文内容。那么如何知道尝试打开 websocket 会话的用户的角色呢?

【问题讨论】:

  • 这是在 JavaEE 7 中吗?强制支持注入等。
  • 支持注入并且我正在使用它,但是您不能注入使用 jax-rs 注入的东西,例如上下文或安全上下文。

标签: security jakarta-ee websocket wildfly


【解决方案1】:

为此,您必须修改 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
}

【讨论】:

  • 搜索这个已经好几个小时了。谢谢!确认在 tomcat 8.5 中工作
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 2016-04-17
  • 2018-11-07
  • 2013-02-07
  • 2012-04-22
  • 2019-06-24
相关资源
最近更新 更多