Limit JSON requests made in an API

Asked

Viewed 629 times

0

I am creating a mini API to make queries on json using ajax, and I’m facing some security issues.

The API is already ready and is returning the data correctly.

The problem is in the file that makes the query, I need to protect it to avoid that some user makes many requests at the same time, because it is a system of CPF queries that needs credits to have the return of the data, and to each query it discounts 1 credit.

If someone uses this script to query multiple CPF, it would be a big problem.

The initial script looked like this:

query js.

function buscarDados(cpf){ 
    if(getCookie('tipo') == 1 || getCookie('tipo') == 2){
        recarregaDados();
        $("#divLoading").hide();
        return true;
    }
    $.ajax({        
        type: "GET",        
        dataType: 'json',   
        async: false,      
        url: "buscar.php?cpf=" + cpf,       
        success: function(data){
            if(data.status == 1){
                setCookie('dadosNome', data.nome, 1);
                setCookie('dadosSexo', data.genero, 1);
                setCookie('dadosNascimento', data.nascimento, 1);
                var nome = data.nome;   
                if(data.genero == 'M')
                    $("#sexo").val('Masculino');
                else
                    $("#sexo").val('Feminino');
                var tmp = nome.split(" ");          
                nome = tmp[0];          
                $("#datadenascimento").val(data.nascimento);            
                $("#inputFirstName").val(tmp[0]);           
                $("#inputLastName").val('');
                for(i = 1; i < tmp.length; i++){
                    if($("#inputLastName").val() != '')
                        $("#inputLastName").val($("#inputLastName").val() + ' ');
                    $("#inputLastName").val($("#inputLastName").val() + tmp[i]);
                }
                $("#nomeCPF").html(nome);     
                $("#divLoading").hide();
            }else{
                if(data.erroCodigo == '102')
                    alert("O CPF informado não existe nas bases de dados da Receita Federal!");
                else
                    alert("Não foi possível realizar a verificação do seu CPF.");
                setCookie('tipo', 0);
                window.location.reload();
                window.reload();
            }
        }, //END success        
        error: function(e){         
            alert("Oops! Não foi possível realizar a verificação do seu CPF.");  
            setCookie('tipo', 0);
            window.location.reload();
            window.reload();    
        } // END error    
    }); // END $.ajax
    return true;
}

The file that performs the query in the API was this way:

search.php

    if($_SERVER['HTTP_REFERER'] == 'url_que_faz_a_consulta' and $_GET['cpf']){

    if(isset($_GET['cpf'])){
        $url = 'https://url_api/cpf/' . $_GET['cpf'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        echo $data;
    }

} else {

include("404.php");
exit;
}

When the user fills the CPF in the form, he will return the data and already fill in the form automatically.

How could I protect this PHP file to block any attempt to perform multiple queries at the same time?

I already have a recaptcha, but it protects only on the form. If the user takes the php URL that makes the query, he will be able to do it, then he would have to find a way to do this validation directly in PHP.

I put a little validation of HTTP_REFERER, but it is not safe enough since the Referer can be changed easily.

Any idea what can be done/implemented? Sessions, limit queries by IP? What would it look like?

  • You can use Cloudflare’s Rate Limiting service: https://www.cloudflare.com/rate-limiting/

1 answer

-1

Have you ever thought of an Entity(Table) USER with each user’s credentials and Credit amount? , that is, before doing the FINAL search, the script checks if the user is registered and if his number of credits is greater than 0. If the user is registered and has enough credits, performs the CPF search.

Browser other questions tagged

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