0

I am creating a SPA blog website with PHP/MySQL and a Javascript frameworks, still haven't decided which one yet.

The idea is that I am willing to create an API and consume it using Javascript, but I want to protect the API, so that no one can access /posts/ for example and get a list of all the posts.

I am not requiring any registration and I don't have a users system.

How would I go about it?

Thanks

Roy5
  • 51
  • 1
  • 6
  • If public javascript can access it, anyone can access it. Either you have some form of membership / authorization, or its public – Steve Jun 09 '16 at 13:16
  • For the APIs you should start using `oauth server` where even to access the public end point it would require `access token` and you can generate the token based on the scope and grant type. – Abhik Chakraborty Jun 09 '16 at 13:25

3 Answers3

0

You might be able to hard code whitelisted IP addresses, but as Steve pointed out in the comments: it's either public or it's not.

I'd go with some little registration functionality that generates API-keys that can be used to access your API.

Loek
  • 4,037
  • 19
  • 35
0

It has been pointed out that a public API is public, however there are some steps that could take to make it more difficult for consumers other than your UI to access it.

The problem is akin (though not the same as) Cross Site Request Forgery, and you can use a variation of any of the prevention techniques listed to mitigate unauthorized access to your API.

The simplest implementation might be something like this:

index.html

<?php 
    $mytoken = uniqid();
    $_SESSION['token'] = $mytoken;
?>
<input type='hidden' name='apitoken' value='<?= $mytoken;?>' >

some-api-endpoint.php

<?php
    if($_GET['apitoken'] !== $_SESSION['token']) {
        header("HTTP/1.0 403 Forbidden", true, 403);
    }

If someone wants to access your public API, they will be able to, but they will have to put forth at least a little bit of effort to do so.

trey-jones
  • 3,329
  • 1
  • 27
  • 35
0

Using a JWT service will work just as well.

Have a look here: introduction to JWT

You can also use an api key and secret which will be passed on initial session auth for your service.

Here's a Stackoverflow answer that helps explain what you'll need to do: key and secret in php

If you're really lazy, you can just use basic authentication or digest auth to auth on the client side. (This is not advisable and has security risks as if you're not using ssl the passwords are passed as plain text in the request)

Another article for your information: PHP HTTP Authentication

Community
  • 1
  • 1
vsharper
  • 307
  • 1
  • 13