I am trying to create a chat app using spring websocket and stomp.
I am using Spring 4.1.1,Stomp.js, ActiveMQ 5.9
In this user can send message to each of his/her friends, who are also logged in, by logging into the app.
For sending message to particular user I take following steps:
1) User logs in
2) User subscribes to "/user/queue/messaging" destination.
This will be used to send private messages of users to each other.
3) when user wants to send a message he sends it to destination :
/user/{user_id}/queue/messaging where user_id is recipients user id.
I am trying to send this from client using STOMP.js send method.
4) Expected behaviour : now if recipient is logged in and his session id, for example, is DFT0GH then the message in step e should be delivered to Queue destination with name messaging-userDFT0GH. Instead of this it is delivered to the same user's queue destination who sent it.
Please find my example scenario :
1) User John logs in .
He subscribes to /user/queue/messaging
His user id is john
His session id is ABCD01
Queue is created with name on activemq broker as
messaging- userABCD01
2) User Alice logs in .
She subscribes to /user/queue/messaging
His user id is alice
Her session id is XYZ01
Queue is created with name on activemq broker as messaging- userXYZ01
3) user John sends a message through STOMP.js send method to Alice
using destination as "/user/alice/queue/messaging"
4) now instead of delivering the message to queue
messaging- UserXYZ01 it gets delivered to John's queue destination i.e
messaging- userABCD01. Why is it so?
When i debugged this , I found following line in method
private DestinationInfo parseUserDestination(Message message) of DefaultUserDestinationResolver class :
if (SimpMessageType.MESSAGE.equals(messageType)) {
........
sessionIds = (sessionId != null ?
Collections.singleton(sessionId) : this.userSessionRegistry.getSessionIds(user));
}
In this sessionId is logged in user's (Principal) session id which is not null as user is logged in and so his sessionIds is returned and message is delivered to his queue even if intended recipient user is different.
When i check usersessionregistry's sessionIds collection I find an entry [alice]:XYZ01.
Shouldn't above line return session id if the user instead of logged in user's session to identify destination queue.?
Sorry I am trying this for the first time. So Please let me know if I miss anything here and of there is
1) any way to satisfy my use case
2) or my use case itself is invalid.
Thanks in advance.
Just so this question stays out of the unanswered list - this is indeed a bug and you raised it as SPR-12444.
This will be fixed in Spring Framework 4.1.3.
As a side note, I'd like to point out that if you're deploying your application with multiple instances, session registries are not shared between instances by default - so this will cause issues when sending a message from a alice (with a session to server #1) to bob (session to server #2).
Related
I have been following this for reference. I am developing a spring-boot app which will have authenticated users. Once logged in, a user will subscribe to an event by visiting a specific URL.
This spring-boot app will also either support MQTT (or maybe just HTTP requests) in which information for a specific user will be sent. I would like to then display this sent information to the user using web flux/SSE if the user has subscribed.
Many users can be logged in at any given time, and they will have all subscribed to the updates. How do I manage all the different sinks for each logged in user?
I believe it's possible to get the current user when they visit the authenticated URL, but what's a method of storing all of the sinks for each logged in user?
I appreciate it.
You already got the answer in the comment section.
Lets assume that this is the message format you would be publishing.
public class Message {
private int intendedUserId;
private String message;
// getters and setters
}
Just have 1 processor and sink from the processor.
FluxProcessor<Message> processor;
FluxSink<Message> sink;
Push all the messages via the sink.
sink.next(msg);
Your controller would be more or less like this. Here I assume you have some method to get the user id authtoken.getUserId(). Here the filter is part of the Flux.
#GetMapping(value = "/msg", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Message> getMessages(){
return processer
.filter(msg -> msg.getIntendedUserId() == authtoken.getUserId());
}
I cloned a chat application project that uses spring boot websocket on github.
Here is code:
#MessageMapping("/chat.private.{username}")
public void filterPrivateMessage(#Payload ChatMessage message, #DestinationVariable("username") String username, Principal principal) {
message.setUsername(principal.getName());
simpMessagingTemplate.convertAndSend("/user/" + username + "/exchange/amq.direct/chat.message", message);
}
Example: username variable is: foo#gmail.com, it mean the link to for client subscribe should be: /user/foo#gmail.com/exchange/amq.direct/chat.message
But in client code:
chatSocket = Stomp.over(new SockJS(url)); //use sockjs and stompjs
chatSocket.subscribe("/user/exchange/amq.direct/chat.message"
I do not understand how to the application can send to correct client, when the client listen the different url (without foo#gmail.com).
Can someone explain to me?
Thanks.
The key is the /user/ prefix in the subscribe url, which will be transformed by Spring to deliver the message to the specific user. It is described in the User Destinations section in the docs:
An application can send messages targeting a specific user, and Spring’s STOMP support recognizes destinations prefixed with /user/ for this purpose. For example, a client might subscribe to the destination /user/queue/position-updates. This destination will be handled by the UserDestinationMessageHandler and transformed into a destination unique to the user session, e.g. /queue/position-updates-user123. This provides the convenience of subscribing to a generically named destination while at the same time ensuring no collisions with other users subscribing to the same destination so that each user can receive unique stock position updates.
I'm having a hard time trying to understand how a user can send a message after login since there is no exchange of a session token or any other kind of token.
For example, in PHP after you login a user, a Session ID is created for him which is stored in a cookie, and then everytime he visits a page, that Session ID is retrieved from the cookie, identifying him.
How does this work with XMPP/ejabberd since no token is exchanged after authentication?
I found this:
Session Manager:
This module routes packets to local users. It searches for what user resource
packet must be sent via presence table. If this resource is connected to this
node, it is routed to C2S process, if it connected via another node, then the
packet is sent to session manager on that node.
... but I'm not sure it is related to my question and even if it is, I still don't get how does this relate to the login the user just made.
In XMPP, a TCP connection is kept open (often with TLS encryption). Every message sent over that connection is assumed to be from the user that has authenticated.
Session support given by the urn:ietf:params:xml:ns:xmpp-session namespace is deprecated and most servers do nothing in response to <session/>.
I am trying to learn websockets with Go. I have been looking at examples with gorilla websocket.
I have checked out these 2 examples that show how to use gorilla websocket:
https://github.com/gorilla/websocket/tree/master/examples
https://www.youtube.com/watch?v=ysAZ_oqPOo0
All of these examples show how to connect to a websocket server, send and receive texts. But what I don't understand is how you can send to only one client. Because in a real world application you will have users, and we don't want all users to receive the same message and same data. Is there a way for me to get the unique id of a connection which I can save in a database like redis and link it to a user id in the same database, and then use that websocket id to send back to a specific client if that user id received a message or a notification? Is this how one would go about and achieve something like this? If that is the case, how would I that?
Is there a way for me to get the unique id of a connection which I can
save in a database like redis and link it to a user id in the same
database, and then use that websocket id to send back to a specific
client if that user id received a message or a notification?
Sure! You can generate Id by yourself while user registering. Just add userId field in connection structure
In chat example you have hub, which contains connections pool. That pool is using to broadcast messages to all users:
case m := <-h.broadcast:
for c := range h.connections {
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
}
}
}
So there you go. You should make method to send private message, depend on userId
I wrote a small project that uses Spring MVC 4 with Websockets and RabbitMQ as the broker.
I am trying to send back to a single user (convertAndSendToUser) but I can't seem to have it working. Here is what the application does:
authenticate to Spring Security over HTTP. The authentication is over AJAX and the backend assigns a UUID as the username to every new connection. There might be multiple clients with the same username so I would like to be able to target individual browsers although they may be logged in with the same username
after authenticating over AJAX the webapp connects to the APIs using STOMP over Websockets.
These are the headers that get send back in the CONNECT FRAME
body: ""
command: "CONNECTED"
headers: Object
heart-beat: "0,0"
server: "RabbitMQ/3.3.1"
session: "session-OGzAN6T8Y0X9ft3Jq04fiQ"
user-name: "88dc9424-72e3-4814-be8c-e31dbf89b521"
version: "1.1"
As you can see there is no frame-suffix or session-id field.
When I use convertAndSendToUser from the backend, the response is send to a unique queue like: /exchange/jobs-userh6g_48h9. The queue name is /exchange/jobs but Spring automatically attaches the suffix -userh6g_48h9. The username is "user" and the sessionId is "h6g_48h9" This is fine and I want this behavior but the problem is that the client (webapp) doesn't get this session id in the CONNECT frame and there is no way for it to actually subscribe to that unique queue.
How to solve this? I want the queue-suffix/session id sent back to me on connect so that the client can get this suffix and subscribe to his unique queues. Currently no messages come back from the server because of this lack of information.
Correct me if I'm wrong, but due to the UserDestinationMessageHandler, clients should be able to subscribe to /user/exchange/jobs and that message handler will correct the queue name for you.
As a side note, you should also consider adding a configuration class extending AbstractSecurityWebSocketMessageBrokerConfigurer similar to the following:
#Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.antMatchers(SimpMessageType.MESSAGE, "/topic/**", "/queue/**").denyAll() // Prevent users sending messages directly to topics and queues
.antMatchers(SimpMessageType.SUBSCRIBE, "/queue/**/*-user*", "/topic/**/*-user*").denyAll() // Prevent users from subscriptions to private queues
.antMatchers("/user/queue/errors").permitAll()
.anyMessage().hasRole("ANY_OPTIONAL_ROLE_ETC")
;
}
}
This will prevent "enterprising" users from subscribing to things that they shouldn't.