如何在websocket open方法中获取当前用户的id?

时间:2015-07-25 04:32:09

标签: java websocket shiro

我试图在websocket的open方法中获取用户ID,为此我使用的是shiro,但是对于Subject我得到null,这是我的方法:

len-1

有人知道我应该做什么吗?

2 个答案:

答案 0 :(得分:5)

经过一天我解决了它,我改变了开放方法的类别:

@ServerEndpoint(value = "/chat/{room}", configurator = GetHttpSessionConfigurator.class, encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class) 
public class ChatEndpoint {

private final Logger log = Logger.getLogger(getClass().getName());

@OnOpen
public void open(final Session session,
        @PathParam("room") final String room, EndpointConfig config) {

    log.info("session openend and bound to room: " + room);

    Principal userPrincipal = (Principal) config.getUserProperties().get(
            "UserPrincipal");
    String user=null;
    try {
         user = (String) userPrincipal.getName();
    } catch (Exception e) {
        e.printStackTrace();
    }
    session.getUserProperties().put("user", user);
    System.out.println("!!!!!!!! "+user);

}}

和GetHttpSessionConfigurator类:

public class GetHttpSessionConfigurator 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"));  
}}

并从Principal实现我的用户模型并覆盖getName()方法以获取id:

@Override
public String getName() {
    String id=Long.toString(getId());
    return id;
}

答案 1 :(得分:0)

一个更简单的解决方案是使用javax.websocket.Session.getUserPrincipal(),该方法返回此会话的已验证用户,如果未为此会话验证任何用户,则返回null

>
redis.execute_command('ZADD', set_name, 'NX', score, key)

诸如onMessage之类的后续方法也可以使用相同的方法来检索用户。