API Design: HTTP Basic Authentication vs API Token

Simone Carletti picture Simone Carletti · Feb 11, 2011 · Viewed 69.9k times · Source

I'm currently creating an authentication system on front of a public web API for a web application. Given that each user account has an API key and each request must be authenticated, I have two alternatives:

  1. Using an HTTP Basic Authentication, like GitHub does.

    Requests must be sent to the URL

    http://api.example.com/resource/id
    with basic authentication
    username: token
    password: the api key
    
  2. Passing the API Token as querystring parameter.

    Requests must be sent to the URL

    http://api.example.com/resource/id?token=api_key
    

There's also a third option which is passing the token within the URI, but I honestly don't like that solution.

Which solution would you adopt and why?

Answer

Yarin picture Yarin · Dec 24, 2013

Best bet might be using an API key in the header (e.g. 'Authorization: Token MY_API_KEY') instead of as a url param:

Advantages over HTTP Basic Auth:

  • More convenient, as you can easily expire or regenerate tokens without affecting the user's account password.
  • If compromised, vulnerability limited to API, not the user's master account
  • You can have multiple keys per account (e.g. users can have "test" and "production" keys side by side.)

Advantages over API key in URL:

  • Provides extra measure of security by preventing users from inadvertently sharing URLs with their credentials embedded in them. (Also, URL can wind up in things like server logs)