how to get id of current user in websocket open method?

为君一笑 提交于 2020-12-29 16:39:35

问题


I am trying to get user id in open method of websocket, and for this I am using shiro, but I get null for Subject,Here is my method:

@OnOpen
public void open(final Session session, @PathParam("room") final String room) {
    Subject currentUser = SecurityUtils.getSubject();
    long id = currentUser.getPrincipals().oneByType(model.Users.class)
            .getId();

    log.info("session openend and bound to room: " + room);
    session.getUserProperties().put("user", id);

}

Does anybody have any idea what I should do?


回答1:


After a day I solved it, I changed class of open method to this:

@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);

}}

and GetHttpSessionConfigurator class:

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

and Implement my user model from Principal and override getName() method to get id:

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



回答2:


A simpler solution could be to use javax.websocket.Session.getUserPrincipal() which Returns the authenticated user for this Session or null if no user is authenticated for this session Like so,

@OnOpen
public void open(final Session session, @PathParam("room") final String room) {
    Principal userPrincipal = session.getUserPrincipal();
    if (userPrincipal == null) {
        log.info("The user is not logged in.");
    } else {
        String user = userPrincipal.getName();
        // now that your have your user here, your can do whatever other operation you want.
    }
}

Subsequent methods like onMessage can also use the same method to retrieve the user.



来源:https://stackoverflow.com/questions/31622958/how-to-get-id-of-current-user-in-websocket-open-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!