Search code examples
ajaxapiauthenticationtokenrestful-authentication

Authenticating an API request with a Token


Suppose I make an API request to the following URL:

https://myapi.com/data

This is an API I built and have full control over.

I would like to limit access to this API to only the apps I authorize.

I see many services will provide you with an API key which you can append to your URL to give you access.

Suppose I have:

https://myapi.com/data?key=a6reallly7long2string9of0numbers2and4letters

Then on the backend I have something like:

class REST {
    public $ACCESS_TOKEN = 'a6reallly7long2string9of0numbers2and4letters',

    public function Auth($token){

        if($token===$this->ACCESS_TOKEN) return true; 

        return false;
    }
}

If the values match, I allow access.

But all someone would have to do is look at the request the app is making on the client side and they have the token.

Even if I encrypt the token or use one-way hashing, they'll still have the value that decrypts to the correct result.

How does one approach good authentication via URL token for an API?


Solution

  • I would like to limit access to this API to only the apps I authorize.

    What are you looking for is "access authorization". Indeed, an access token seems to be a good way, but there are some aspects missing

    ** Authorization header **

    By default the token should be sent as an HTTP header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) not in the url

    Commonly used Authorization headers types are Basic (for basic authentication) and Bearer (for OAuth authentication and authorization)

    The token should not be a hardcoded constant. It should be created/generated based on the application (and optionally user) authentication. And still better if the token is temporary

    Now you can ask - how can an application keep its credentials secret? Each application can have their own server services (end user should.not access application credentials) or pure web application should be comtrolled by the CORS headers

    Just search for OAuth 2.0 protocol and JWT token (jwt should be self-contained and signed).

    IMHO the URL token may be an option when there is no other alternative, as URL is often cached, resent, logged,...

    ** API Manager **

    If you have resources (server) to do so, you can deploy an API manager (there are open source, commercial or cloud options, just search for some). API manager will handle the application enrollment, authorization and enforcement.