How to prevent user from accessing JSON data from query parameters?

Viewed 274

I am developing a really simple webapp that searches for a company's stocks.

Here is the JS code (uses AJAX to fetch the company's stock from the server):

document.getElementById("requestQuoteBtn").addEventListener("click", function createQuoteRequest(){
    var quoteSymbol = document.getElementById("requestedSymbol").value;
    var quoteRequest = createAJAX();

    quoteRequest.open('GET', '/quote?sym='+quoteSymbol);
    quoteRequest.send();

    quoteRequest.onload = function getQuoteRequest(){
        if(quoteRequest.status == 200){ // SUCCESSFUL
            displayQuoteData(false, JSON.parse(quoteRequest.response)); // basically shows a hidden div with the data
        }
        else // NO COMPANY W/ THIS SYMBOL FOUND
            displayQuoteData(true, null);
    };
});

Here is the Flask code:

@app.route("/quote", methods=["GET"])
@login_required
def quote():
    requestedSymbol = request.args.get("sym")
    if not requestedSymbol:
        return "no symbol"

    quoteData = lookup(requestedSymbol) # USES AN API TO FETCH COMPANY'S STOCK

    if quoteData is None:
        return "NONE", 404
    else:
        return quoteData

The issue is that if the user accesses, for example, this URL:

www.mywebsite.com/quote?sym=AAPL

It will literally show a raw HTML with JSON's data, instead of my website with the data:

{"name":"Apple, Inc.","price":"$245.18","symbol":"AAPL"}

How can I prevent this?

1 Answers

If you simply want to make sure that users do not accidentally access your api endpoint when trying to access your website (aka this is about user experience and your not concerned with adding auth to your API endpoint)

The easiest way is to create separate routes for your api and your client routing

Update:

@app.route("/api/quote", methods=["GET"])

Likewise update:

quoteRequest.open('GET', '/api/quote?sym='+quoteSymbol);

Your client routing will still be:

@app.route("/quote", methods=["GET"])

If you want to make sure that nobody can access your api endpoint then you need to add some sort of authorization to your endpoint.

If you do not secure your API with some authorization then anyone can access the data you return from your server API simply by visiting the route.

Either way setting up separate routes for your API endpoints and client side routes should solve the problem of showing API data instead of your client template when visiting:

mywebsite.com/quote?sym=AAPL

Related