Protecting API/Route against direct access?

Posted 3 months ago by jelledv4

I'm building a tool that gives you a list of random words. When you click on the button (in a blade template), an jQuery AJAX request is sent to the '/api/words' route, which returns a JSON object with an array of the words. Those words are put into a div using jQuery.

How can I protect users from directly using the API to get words from it and only allow the API route '/api/words' to be accessed from that specific page through an AJAX call?

I don't want people to use the API route for themselves from the outside/directly.

My first idea was a CSRF token, but that's not an option for GET requests, right? What about attaching a special token similar to CSRF token?

Code:

  • home.blade.php
<div id="word-list"></div>
<button id="fetch-words-btn">Fetch words</button>

<script>
$("#fetch-words-btn").click(function() {
    $.ajax({
        url: "/api/words",
        type: "get",
        data: {
            amount: 10
        }
    })
    .done(function(response) {
        response.words.forEach(function(element) {
            $("#word-list").append("<li>" + element + "</li>");
        });
    })
    .fail(function(response) {
        console.log(response);
    });
});
</script>
  • api.php
Route::get('/words', '[email protected]');
  • WordController.php
function index()
    {
        $params = request()->validate([
            'amount' => 'required|integer|min:1|max:20'
        ]);

        $words = file(storage_path().'/app/txt/words.txt', FILE_IGNORE_NEW_LINES);

        $result = [];
        for($i=0; $i<$params['amount']; $i++) {
            $result[$i] = $words[rand(0, count($words)-1)];
        }

        return response()->json([
            'words' => $result
        ]);
    }

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.