Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
check if urls have the same origin

I have a function that runs before every API request to check if the request is from a valid origin.

I have an array of valid origins

const whitelist = [ 'a.com', 'b.co.uk' ]

const validOrigin = str => {
    const url = new URL( str )
    return whitelist.includes( url.host )
}

console.log(validOrigin('https://www.a.com'))

It returns false because of the www. I dont want to just add a copy with www. to the array of valid origins. I would like a way that covers this and everything else thats unexpected.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Keeping in mind that, by the rules, www.example.com and example.com are different origins:

If you want to match any origin on the same domain or a subdomain of the domains in the whitelist, then you need to:

  • Strip off the scheme and port - which you are doing already
  • Check for an exact match - which you are doing already
  • Check for a match which ends in . followed by the string (to stop third-party-hacker-a.com matching)

So something like:

const validOrigin = str => {
    const url = new URL( str )
    const host = url.host;
    return whitelist.some( element => {
        if (element === host) return true;
        return element.endsWith(`.${host}`);
    } )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The Array.prototype.includes function only accepts the value to search for, and looks for an exact match.

You would need to use a function that accepts a callback to test the elements - for example, the Array.prototype.findIndex function.

As you mention in the comments, you'll also need to change the whitelist so that you can exclude domains whose name ends with one of your valid domains.

const whitelist = [ /(^|\.)a\.com$/i, /(^|\.)b\.co\.uk$/i ];

const validOrigin = str => {
    const url = new URL(str);
    const index = whitelist.findIndex(el => el.test(url.host));
    return index !== -1;
};

document.querySelectorAll("#tests > li").forEach(li => {
  const str = li.dataset.value;
  const result = validOrigin(str);
  li.textContent = `${str} = ${result}`;
});
<ul id="tests">
  <li data-value="http://a.com/foo"></li>
  <li data-value="http://www.a.com/foo"></li>
  <li data-value="http://dev.a.com/foo"></li>
  <li data-value="http://banana.com/foo"></li>
  <li data-value="http://a.com.b.ru/foo"></li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can try something like this

str = str.replace( new RegExp("((http)(s)?:\/\/)?(www.)?","gm"),"")

this will delete the first part of the url

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda