如何在websocket open方法中获取当前用户的ID? [英] how to get id of current user in websocket open method?

查看:76
本文介绍了如何在websocket open方法中获取当前用户的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 websocket 的 open 方法中获取用户 ID,为此我使用了 shiro,但我的主题为 null,这是我的方法:

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?

推荐答案

解决了一天后,我把open方法的class改成了这样:

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

}}

和 GetHttpSessionConfigurator 类:

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

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

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

这篇关于如何在websocket open方法中获取当前用户的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆