Simple API Authentication with Drupal

One of our smaller projects required us to expose some data, this exposed data would be used by a few other sites / applications to keep their internal data up to date. We were using Drupal to export the data (really easy with views and views_data_export), but anyone with the URL would be able to access the data. Which, in this case isn't a huge problem, but it's not ideal.

So to resolve this problem we implemented a basic token authentication system. This allows the client to distribute a token to each app / site they want to be able connect to the data. It also provides a way to revoke tokens should any problems arise. Whilst we wouldn't recommend this approach for any large API, or any API providing sensitive information - for this situation it was ideal.

The three modules required for this solution are views, views_data_export and taxonomy.


Create a new taxonomy called API Apps (or anything you want really).

I would recommend adding a text field to the taxonomy term called app name or something - this will come in useful later.


Create your data export view as normal - ensure it's exporting everything you need.

Add a "global null" contextual filter to the view (this can be in addition to any other contextual filters you may have)

Adjust your path, I like to have my-view/token/% or my-view/%/token/% if I have an existing contextual filter

You MUST require ALL contextual filters to be set - either display access denied or a 404 if they are not present

On our contextual filter, under "When the filter value IS in the URL or a default is provided" - specify a validation criteria. Set validator to "Taxonomy Term", select our "API Apps" vocabulary, then "Filter value type" is set to "Term name converted to Term ID". Finally, set to either access denied or page not found if the validation fails.

Save the view.


Add a term to the vocabulary you created before, for the name - enter a token. For this purpose, just hash a random number. Then enter an app name under the field we created before (this is purely to make our lives easier), save the term.

Back to our view and we are able to test - entering the token in the preview should reveal our data.

Excellent - that's everything up and running, our data is protected by token(s) that we can give out to the various apps. Deleting the term will revoke the token and access to the data.

Taking it Further

Add some more fields to the term that hold date(s) of activation.

Create a new administration view that display the tokens, app name and date(s) - with nice links to revoke, update or add new terms.


Hope this helps someone create a basic token authentication view - any questions let me know in the questions below.