Search code examples
javascriptsecuritykey

How do I set up an API web key with URL authentication in JavaScript and PHP?


My backend is PHP

I have a service that I want to put out online lets call it GREATSERVICE.com. I want to have people sign up for an API key and restrict it by domain so that only http://www.????.com can use it. I know I can just store the API and domain that the person enters into the database.

I'm hung up on how to validate that the service is being accessed by the proper web site.

I mean lets say I'm cruising the web with the domain address temp-13-43.xfinity.com and I go to website servicehost.com. servicehost.com has an API key....as how do I recognize the service is being accessed from servicehost.com and not the clients temp-13-43.xfinity.com address...

So what I'm trying to figure out is to this in JavaScript on the client side. Kind of like Google Maps. Maps just loads some JavaScript onto the page with an API key but the API key checks the URL of the WEB SITE and not the client visiting the website.

That is where I'm lost. How can I check the DOMAIN of the site that the user went to and only if it is correct wiht the correct API then render the service out.

So in the head section I have JavaScript

So on the SERVICEHOST site I give them the code so that they can use the mygreatservice widget. Think along the lines of the twitter embedded viewer

<SCRIPT type="text/javascript" src="http://mygreatservice.com/service.php?api=asdfasdfasdfa></SCRIPT

Tags which point to a PHP page to return the need JavaScript. Again I just want to make sure that the widget I'm returning is used on the proper sites for light security/tracking purposes.


Solution

  • Edit:

    Ask your members to put this line in their site: (for instance I put this code in my server http://www.otherserver.com)

    <script language="javascript" src="http://yourserver.com/service.php?token=342424adsasjdl34"></script>
    

    In your service.php file (hosted on your server):

    $server = $_SERVER['SERVER_NAME']; // =www.otherserver.com
    $apitoken = $_GET['token']; // the token 342424adsasjdl34 (don't forget to make it safe!)