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.
Related
As part of our effort to be GDPR compliant, I’m trying to extend our Keycloak server with some custom functionality, to be triggered when a user is removed:
sending a confirmation message to a Slack channel
sending a HTTP request to another service we built, to delete any assets that user might have created there
The first one was easy. It's implemented as a SPI event listener, following this example:
#Override
public void postInit(KeycloakSessionFactory keycloakSessionFactory) {
keycloakSessionFactory.register(
(event) -> {
// the user is available via event.getUser()
if (event instanceof UserModel.UserRemovedEvent){
userRemovedMessageHandler.handleUserRemoveEvent(session, (UserRemovedEvent) event);
LOG.debug("User removed event happened for user: " + ((UserRemovedEvent) event).getUser().getId());
}
});
}
But I'm stuck on the second task (sending the HTTP request). The other service is set up to require a trusted client token, using a designated Keycloak Client and scope. The equivalent POST request to auth/realms/{realm}/protocol/openid-connect/token is done with these parameters:
grant_type: password
username: {user that is about to be deleted}
password: {user password}
client_id: {the specific client}
client_secret: {that client's secret}
scope: usersets
I can’t find out how to do that from within the SPI code. I can retrieve a regular Access Token (as described in this other SO post):
private String getAccessToken(KeycloakSession session, UserModel deleteUser) {
KeycloakContext keycloakContext = session.getContext();
AccessToken token = new AccessToken();
token.subject(deleteUser.getId());
token.issuer(Urls.realmIssuer(keycloakContext.getUri().getBaseUri(), keycloakContext.getRealm().getName()));
token.issuedNow();
token.expiration((int) (token.getIat() + 60L)); //Lifetime of 60 seconds
KeyWrapper key = session.keys().getActiveKey(keycloakContext.getRealm(), KeyUse.SIG, "RS256");
return new JWSBuilder().kid(key.getKid()).type("JWT").jsonContent(token).sign(
new AsymmetricSignatureSignerContext(key));
}
but that's not the token I need. In order to retrieve the required trusted client token I’d need the internal Keycloak / SPI-equivalent of the above POST request, but I can’t figure out how to do that or where to look.
Besides, I'm not sure if it is even possible to retrieve a trusted client token for a user that is in the process of being deleted. In other words, I don’t know if the UserRemovedEvent is fired before, during or after the user is actually deleted, or if Keycloak waits until any custom EventHandlers have finished running.
(In order to figure that out, I'll try if it is possible to retrieve that token using a regular http POST request from within the add-on code, but I have no idea if it's possible to connect to Keycloak like that from inside. I'll update the question if that works.)
I'd greatly appreciate any suggestion!
(I also asked this in the Keycloak discourse group here but it looks as if it will remain unanswered there)
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 really wonder if there is a way to customize a message in SESSION_EXPIRED_STATUS from WebSocketRegistryListener. The default implementation is follow:
static final CloseStatus SESSION_EXPIRED_STATUS = new CloseStatus(
CloseStatus.POLICY_VIOLATION.getCode(),
"This connection was established under an authenticated HTTP Session that has expired");
The Spring Security and Spring Session mechanisms are:
User logouts
The corresponding session is invalidated in session repository
WebSocketRegistryListener catches SessionDestroyedEvent and closes all websocket sessions for previously destroyed http session (with close status SESSION_EXPIRED_STATUS)
So, in my application I should customize such behavior, because not only the user can invalidate his session, but also admin is able to do it. Or session can be invalidated by timeout. And for every case I should send messages with different reasons. Can someone help me?
I found WebSocketSessionDecorator with close(CloseStatus status) but I don't know to add it to decorators list for websockets.
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 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).