handshakecometd

Cometd additional info during handshake


My app uses JWT for auth. The app is react on the frontend and spring on the backend. Recently i added push functionality using cometd, 7.0.10, and am running into an issue. As part of the cometd handshake and i send the jwt token, like so

var additional = {
    "com.app.credentials": {
        "token": localStorage.getItem('token')
    }
};
cometd.handshake(additional, function(handshakeReply) {
    if (handshakeReply.successful) {
    }
});

Now the problem is that the token is taken from localstorage when the page is first loaded - at that time the token is valid and there is no issue - the token is received by the server and the appropriate security checks are done (related to cometd). However, the token is refreshed periodically, and after that happens if there happens to be a cometd handshake, then the token sent is the old one (set during 1st page load) - the correct one is available in localstorage. Since its the old one, the server side rejects it. Note this only affects cometd - the REST API's called by the JS to springboot all works well. If i reload the page then there is no issue - but i dont want to do that.

If the 'additional' param passed into cometd.handshake was a function that was invoked everytime cometd needed the additional params then it would solve my issue.

I am also assuming that one can invoke cometd.handshake only once.

Anyone help on how to resolve this would be fantastic.


Solution

  • If the 'additional' param passed into cometd.handshake was a function that was invoked everytime cometd needed the additional params then it would solve my issue.

    Indeed.

    const additional = () => {
      const token = localStorage.getItem('token');
      return {
        "com.app.credentials": {
          "token": token
        }
      }
    }
    
    cometd.handshake(additional(), handshakeReply => {
      if (handshakeReply.successful) {
        ...
      }
    });
    

    Basically, you want to make additional a function that when invoked performs the lookup of the token in localStorage, so that it always retrieves the latest value.