Sharing JWT between Cross-Port Applications using postMessage

301 views Asked by At

I have two applications running on my localhost, each on a different port (localhost:3000 and localhost:3002). My goal is to redirect a user from localhost:3000 to localhost:3002 while passing a JWT (JSON Web Token) between the two applications. However, my current implementation using the postMessage method isn't working as expected.

Here's what I've tried:

Sender (localhost:3000):

        const targetWindow = window.open("http://localhost:3002", "_blank");

            if (targetWindow) {
                targetWindow.addEventListener("load", () => {
                    const jwtToken = "my_jwt_token";
                    targetWindow.postMessage({ jwtToken }, "http://localhost:3002");
                });
            }

Receiver (localhost:3002):

  useEffect(() => {
    window.addEventListener("message", (event) => {
      if (event.origin === "http://localhost:3000") {
          const { jwtToken } = event.data;
        }
    });
  }, [])

However, I'm not seeing any messages in the console when I print the "message" event. Could you please help me identify what might be causing this issue? Is there a better approach to achieving my goal of sharing a JWT between these two applications running on different ports?

Any insights or guidance would be greatly appreciated.

2

There are 2 answers

0
Amir Ben Shimol On BEST ANSWER

I shared the jwt token throw cockles using universal-cookie

Sender (localhost:3000):

const jwtToken = 'your_jwt_token_here';
const cookies = new Cookies();
cookies.set('jwtToken', jwtToken, { path: '/' });

Receiver (localhost:3002):

const cookies = new Cookies();
const jwtToken = cookies.get('jwtToken')

Note: Dont forget to clean the cookies after extracting the jwtToken

2
Zazaeil On

JWT tokens are safe to publish openly, so the pretty standard way to do it is to provide a query parameter: localhost:3002?JWT=my-jwt-token, which later is extracted from there and validated by whatever backends the localhost:3002.

This is the simplest solution I can imagine without hidden unwanted side effects.