As usual, I'll be participating in the comments below, so please offer your thoughts. You can also reach me on Twitter @lookahead_io. I'm always especially intrigued if you want to suggest new features or topics for future tutorials.

As a reminder, all of the code for Meeting Planner is written in the Yii2 Framework for PHP. If you'd like to learn more about Yii2, check out our parallel series Programming With Yii2.

The Initial API Security

Let's begin by taking a look at the early API security I coded. We'll presume there's a mobile app that I've shared an $app_id and $app_secret with. Only API callers with these keys are accepted.

For example, the app tries to register its owner, likely a new Meeting Planner user:

Because the keys and the data were sent via SSL, they're pretty secure but not invincible. Neither is the secret key safe on users' iPhones for certain.

How can we make this more secure? Here are a few ideas:

Don't ever transmit the secret key over the Internet.

Don't transmit any of the data as URL parameters which might show up in server logs.

Sign all the data to verify its accuracy.

These are actually standard practices used for securing APIs.

Note: An example of the risk of transmitting data that could be exposed in server logs would be the email and the Facebook OAuth token. If found in logs, these could be used with the Facebook API to access someone's Facebook account.

Implementing Better API Security

Using Hash Signatures

First, I'm going to stop transmitting the $app_secret. Instead, we'll sign the outgoing data with it before making an API call.

So we'll alphabetize the variables and concatenate them into a string, like this:

$data = $email.$firstname.$lastname.$oauth_token.$source;

Resulting in:

$data = 'tom@macfarlins.comthomasmacfarlinszuckerburgerzuckerburger'

Then, we'll hash the data with PHP's hash_hmac and the sha256 algorithm using our secret key.

Furthermore, as I reviewed last time, each user receives their own token when they access Meeting Planner through the API, e.g. via their mobile phone. So, subsequent to registration, we can sign calls with their individual token and don't need to transmit either the application's secret key or the user's individual token.

Sending Data in the HTTPS Headers

Next, we'll migrate sending data in the headers. You can do this easily with Postman or cURL. Here's Postman:

In Closing

Don't transmit any of the data as URL parameters which might show up in server logs.

Sign all the data to verify its accuracy.

And we accomplished all of these goals with only modest changes to our API code. It was fun making these changes and seeing how easily we can better secure an API. I hope you enjoyed following along with today's episode.