Phate
Phate

Reputation: 6612

How to correctly implement security on a websocket session?

I want to implement an asynchronous mechanism using websockets. Here's the idea:

  1. The client performs a REST call
  2. The server returns a "subscribingID" and starts a background process
  3. The client registers as subscriber on this topic (suppose 12232442 is the id):

    this.stompClient.subscribe('/callback/12232442', (messageOutput) => {
        let mess = JSON.parse(messageOutput.body);
        console.log(mess);
    });
    
  4. Once done the server simply sends the message and closes the connection:

    stompSession.send("callback/12232442", new MessageOutput());
    

It should work but here's the catch: how can I be sure that another client can't simply subscribe to an ID that exists but does not belong to them?

Also, is there any built-in mechanism to achieve this?

Upvotes: 0

Views: 147

Answers (1)

srinivas kumar
srinivas kumar

Reputation: 423

  1. When the server receives a REST request for a subscription ID, you can store the newly generated ID in a Subscription HashMap.

  2. In order to do processing when a new subscription request comes you can implement a custom StompEventHandler, like so

@Controller
public class StompEventHandler{
@EventListener
public void handleSubscription(SessionSubscribeEvent event) {
    //Get incoming sessionDetails from event.
    //get the destination.
    // Validate that the destination is present in Subscription HashMap
    // and also that no client maps to the topic id.
    // Based on the result either send the message or send Unauth message to 
       client.

  }
}

Documentation

  1. Note that you have to store details about session ID of the client as well for this. Instead of broadcasting the message to /topic/callback/<your_id>, you would need to send the message to destination like so: /user/queue/callback/<your_id>. For sending to a destination as such you would need to use simpMessagingTemplate.convertAndSendToUser(username, destination, payload, Headers) Good Read for this

  2. So since you are sending messages to only a particular session of a particular user, your messages are confidential.

  3. If you want to ensure that you do not even have the subscription from the client you can send an UNSUBSCRIBE message to the client in the StompEventHandler class. This would force unsubscribe the client. Good Read for this

Upvotes: 1

Related Questions