Websocket(java ee)如何获得当前用户的角色

der*_*itz 3 security java-ee websocket wildfly

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

但是在websocket中我不能注入上下文的东西.那么如何知道试图打开websocket会话的用户的角色呢?

MSD*_*MSD 6

为此,您必须修改Websocket握手.你可以这样做:

1)修改websocket端点以使用自定义配置程序

@ServerEndpoint(value = "/someWSEndpoint", configurator = SomeCustomConfigurationClass.class)
public class SomeWSService {
...
}
Run Code Online (Sandbox Code Playgroud)

2)修改WS握手类似于

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"));     
    }
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)