我试图在websocket的打开方法中获得用户id,为此我使用shiro,但我得到主题为空,这是我的方法:
@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);
}
有谁知道我该怎么做吗? 一天后我解决了这个问题,我把open方法的类改成了:
@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;
}
一个更简单的解决方案是使用javax.websocket.Session.getUserPrincipal(),其中返回此会话的已认证用户,如果没有用户为此会话进行身份验证,则返回null
@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.
}
}
后续的方法如onMessage也可以使用相同的方法来检索用户