0

I'm building an API for my website and I only want the API to be accessible from my own website. The way I've built it is that I call a PHP file using ajax:

    <?php session_start(); ?>
    <script>
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "secureapi.php",
            data: "test="+document.cookie.substring(document.cookie.lastIndexOf('PHPSESSID')).replace(/phpsessid=/gi, '') + "userid=123",
            success: function(response){
                console.log(response);
            }
        });
    </script>

In the PHP file I then check if it's called from a xmlhttprequest and that the session_id is correct:

<?php

    session_start();

    if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' AND $_POST['test'] == session_id()){
        //QUERY DATABASE AND RETURN JSON
    }

?>

Is this secure enough or can someone easily get the session_id with CURL or something?

Oskar Persson
  • 6,605
  • 15
  • 63
  • 124
  • possible duplicate of [How to restrict AJAX API from unwanted use (e.g. someone performing a SELECT \*)](http://stackoverflow.com/questions/1558278/how-to-restrict-ajax-api-from-unwanted-use-e-g-someone-performing-a-select) – Quentin May 09 '13 at 11:50
  • An API is just as public as your HTML sites. You secure and restrict them the same way too, using authentication cookies and permission checking. – deceze May 09 '13 at 11:53
  • @deceze Yes I know, and I wrote my solution above and now I want to check if that's good enough or easily broken. – Oskar Persson May 09 '13 at 11:56
  • The tests you do are basically pointless. The `X-Requested-With` header is easily spoofed and doesn't secure anything, and if you require a session just start a session as usual and save some value in it; the same regular authentication works. `if ($_SESSION['loggedin'])`... – deceze May 09 '13 at 12:16
  • The user doesn't have to be logged in or have some special permissions. The only restriction is that the call must come from my website. It's not a public API. I really can't find a good solution for my problem. If I would use api-keys then I would have to send it using Ajax which everyone easily can see. – Oskar Persson May 09 '13 at 13:03
  • 1
    An AJAX call doesn't come "from your website". It comes from random clients' browsers! The only thing you *may* be able to look at is the referer, but that's easily spoofable and not any security. Unless you use some sort of token or login system, **your API is public out of necessity.** You wouldn't require your regular web pages to "only be visited by visitors of your site", right? AJAX requests are not any different. – deceze May 10 '13 at 06:50
  • Maybe you should look into my project https://github.com/victorjonsson/PHP-Rocker (it's built on top of Slim) – xCander May 11 '13 at 08:25

0 Answers0