Securely checking the origin of a message posted from another window

2.3k Views Asked by At

My client-side code is receiving a message from another window (an iframe) -- something like this (let's call this page1, or https://my.site/page1):

window.addEventListener("message", function(event) {
    if (event.origin !== ALLOWED_ORIGIN) {
        return;
    }
    // Further logic here
});

The iframe is expected to point to another URL on the same origin as page1, e.g. https://my.site/page2, where at a certain point, page2 client JS executes:

window.top.postMessage(somePayload);

My goal is to ensure that no matter where the iframe ends up pointing (perhaps due to an exploited vulnerability that I didn't notice), my page1 only accepts messages sent from a URL on my domain.

I am thinking of using window.origin as ALLOWED_ORIGIN on page1. It seems easier than having to pass my domain itself from some sort of a config file that I'd have to change for all the different dev, testing environments, and ultimately, prod.

However, I can't find examples from others using this approach, and neither can I find any explanation of why it isn't good enough.

Is event.origin !== window.origin considered not secure enough, and most importantly, why?

My apologies if this is something obvious, and thanks for reading this question!

0

There are 0 best solutions below