How to authenticate via headers and access API

Asked

Viewed 42 times

0

Access to Apis should be done by passing the following data in the request header:

"[{"key":"chave-api-dados","value":"123456789"}]

Please! Where do I add these values for authentication and access the API?

function buscarPorCpf(){

    const cpf = document.getElementById("cpf").value;
    const mesAno = buscaMes();
    const url = "http://www.transparencia.gov.br/api-de-dados/bolsa-familia-disponivel-por-cpf-ou-nis?codigo="+cpf+"&anoMesReferencia="+mesAno+"&anoMesCompetencia="+mesAno+"&pagina=1";

    var ajax = createCORSRequest('GET', url);

    if (!ajax) {
      throw new Error('CORS not supported');
    }
  

    ajax.onreadystatechange = function () {

        if(this.readyState == 4 && this.status == 200){
            console.log(this.responseText);
        if (this.responseText.length < 3) {  
        $('#dados2').hide();   
        $('#novaconsulta').show();
          }
            let resposta = JSON.parse(this.responseText)[0];
            const valor = resposta.valor;
            const nome = resposta.titularBolsaFamilia.nome;
            const cpf = resposta.titularBolsaFamilia.cpfFormatado;
            
            document.getElementById("pcpf").innerHTML = cpf;
            document.getElementById("pessoas").innerHTML = nome;
            document.getElementById("pvalor").innerHTML = valor;



    }


};

    ajax.send();



}


function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();

    if ("withCredentials" in xhr) {
      xhr.open(method, url, true);

  
    } else if (typeof XDomainRequest != "undefined") {
      xhr = new XDomainRequest();
      xhr.open(method, url);

  
    } else {
  
      xhr = null;
  
    }
    return xhr;
  }
  • You included your key in the previous question and I did a test and it is not valid. Check that it is correct and run a test on http://www.portaltransparencia.gov.br/swagger-ui.html. It should be accurate

2 answers

0

Give a googlada to find which method of the class XMLHttpRequest adds headers (headers) to the HTTP request that will be made. Headers are pairs of strings: one is the header key or name, the other is the value.

Call this method on the object xhr passing the key and value as arguments.

Edit: I found it for you:

xhr.setRequestHeader("chave-api-dados", "123456789")

Voilà!

  • I added the code after xhr.open(method, url, true); but returns the error net::ERR_FAILED could give us an example of what the code would look like?

  • Bro, I just gave you the tip, I don’t do Javascript. I think the header problem was solved and the request was sent, but the upload failed due to some network error. You have to search to see what might be. One possibility is these this.readyState and others this that you are calling within the function that treats Ajax’s response to actually be ajax.readyState, etc. I’m not sure. Do a search, accept this answer if you answered it and if so, create a new question.

0


In accordance with the documentation, can add headers to http requests by making: XMLHttpRequest.setRequestHeader(header, value).

The method should be used after open and before send.

Already XDomainRequest does not have a similar method.

Accordingly, and considering that the XDomainRequest is practically no longer supported, one could remove the code snippet that refers to it and do ajax.setRequestHeader("chave-api-dados", sua_chave) before your line ajax.onreadystatechange (...).

  • I tried to make your changes in the code and still without authorization, could give us an example how the code would look?

  • @Igor you included your key in the previous question and I did a test and it is not valid. Check that it is correct and do a test in http://www.portaltransparencia.gov.br/swagger-ui.html. It must be necessary to request the unlocking as http://portaldatransparency.gov.br/data.

  • my key is correct, but I didn’t post the correct key here, can you post here how the code was after you edited? Thanks.

  • Can make a test in portaltransparencia.gov.br/Swagger-ui.html?

  • Yes I did the test, my key is released, the mistake I have now is Access to XMLHttpRequest at 'http://www.transparencia.gov.br/api-de-dados/bolsa-familia-disponivel-por-cpf-ou-nis?codigo='00000000000&anoMesReferencia=202101&anoMesCompetencia=202101&pagina=1' from origin 'http://uni5.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  • In this case @Igor, the request is already being blocked by the browser, because the API does not have a policy to accept requests from any site, which means that you cannot order directly from the Front end. An alternative is to use a proxy. Try changing the api address to https://cors-anywhere.herokuapp.com/(old address with http://)

  • worked! Thank you very much.

  • @Igor, since you were able to confirm that this is the problem, I recommend having a proxy of your own. Abs!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.