Securing your PHP REST API with OAuth

Problem:

There are many considerations to make when building and securing a public-facing API, but I wanted to look at one issue in particular: Making sure that only authenticated clients can access it.

Ideally, we want to make one request to the server and get back one response. In order to have a simpler application flow, we want to avoid the added complexity of managing access tokens.

  1. Client sends a request for data along with their authentication details
  2. Server sends data back to the authenticated client

This flow will be familiar if you have used Amazon Web Services (AWS) before, as they use a similar “signed-message” solution.

Solution:

Use a simple version of the OAuth 1.0 standard which is known as “2-legged” authentication. In this system, no access tokens are used. Authentication is performed using a public and private key system. These public and private keys are known by the client (consumer) and the server (provider).

Things to note:

  • The private key (the secret) is NEVER passed over the wire
  • The private key is used in combination with HMAC to hash the request data being sent to the API
  • The server uses its own copy of the private key to verify the request is authentic
  • You should use SSL to encrypt traffic between your consumer and provider

My solution uses PHP OAuth library by Andy Smith (MIT licence) for the heavy lifting. I have made this library available as a Composer package: https://packagist.org/packages/glenscott/oauth.

Here are two simple examples for the provider and consumer sides:

Provider side

In this example, the list of valid consumer keys and secrets are hardcoded, but you probably want to store these in a DB somewhere. The provider will return "true" if it is a valid authenticated request, or otherwise it will spit out and error message "Exception: ...".

		$server = new OAuthServer(new DataApi_OAuthDataStore());
		$server->add_signature_method( new OAuthSignatureMethod_HMAC_SHA1() );

		$request = OAuthRequest::from_request();

		try {
			if ( $server->verify_request($request) ) {
				echo json_encode(true);
			}
		}
		catch (Exception $e) {
			echo json_encode("Exception: " . $e->getMessage());
		}

		class DataApi_OAuthDataStore extends OAuthDataStore {
			function lookup_consumer($consumer_key) {
				$consumer_secrets = array( 'thisisakey'		=> 'thisisasecret',
										   'anotherkey'		=> 'f3ac5b093f3eab260520d8e3049561e6',
										 );

				if ( isset($consumer_secrets[$consumer_key])) {
					return new OAuthConsumer($consumer_key, $consumer_secrets[$consumer_key], NULL);
				}
				else {
					return false;
				}
			}

			function lookup_token($consumer, $token_type, $token) {
				// we are not using tokens, so return empty token
				return new OAuthToken("", "");
			}

			function lookup_nonce($consumer, $token, $nonce, $timestamp) {
				// @todo lookup nonce and make sure it hasn't been used before (perhaps in combination with timestamp?)
				return NULL;
			}

			function new_request_token($consumer, $callback = null) {

			}

			function new_access_token($token, $consumer, $verifier = null) {

			}
		}

Consumer side

	require_once dirname(__FILE__) . '/../library/OAuth/OAuth.php';

	// this is sent with each request, and doesn't matter if it is public
	$consumer_key = 'thisisakey';

	// this should never be sent directly over the wire
	$private_key  = 'thisisasecret';

	// API endpoint
	$url = 'https://example.com/v1/oauth';

	// the custom paramters you want to send to the endpoint
	$params = array( 'foo' => 'bar',
					 'bar' => 'foo',
					 );

	$consumer = new OAuthConsumer($consumer_key, $private_key);
	$request  = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $url, $params);

	$sig = new OAuthSignatureMethod_HMAC_SHA1();

	$request->sign_request($sig, $consumer, null);

	$opts = array(
		'http' => array(
			'header' => $request->to_header()
		)
	);

	$context = stream_context_create($opts);

	$url = $url . '?' . http_build_query($params);

	echo "Making request: " . $url . PHP_EOL;
	echo "Authorization HTTP Header: " . $request->to_header() . PHP_EOL;
	echo "Response: " . file_get_contents($url, false, $context) . PHP_EOL;

Using the samples above should give you a head-start when creating your own authenticated API.

View the sample code on GitHub.

Any questions? Please use the comments section below!

P.S. – Looking for reliable hosting for your PHP projects? I recommend Clook:

6 Cash Flow tips for Freelancers

Getting paid as a freelancer can often turn into an ordeal, but there are several ways you can make it easier for yourself. Here are some tips to ensure a steady flow of cash into your freelancing business.

1. Invoice Promptly

The later you send an invoice, the later you are going to get paid. So make sure that you get your invoices out in a timely fashion. If producing invoices is a hassle, then get yourself some invoicing software that makes it easy. I personally recommend FreeAgent.

2. Ask for money up front

Ask for a deposit before you start work. This can be anything from 20% up to the full amount. Don’t think the client will give you anything up front? There’s no harm asking. I insist on a project deposit from clients that I haven’t worked with before to minimise my risk.

3. Use payment milestones

If you are working on a project that’s going to run for at least a few weeks, then consider having intermittent payment milestones. Schedule an invoice every week, or every fortnight.

4. Shorten your payment terms

30 days is an awful long time to wait to be paid if you have previously spent weeks, or even months, on a project. Shorten your payment terms to 14 days, or less.

5. Automatically follow up

If an invoice has passed its due date, then follow up with a friendly reminder e-mail. Most invoicing software will have this feature in built saving you the time of following up yourself. Be friendly, but persistent.

6. Charge late payers

At least in the UK, you are legally entitled to charge interest and an optional fee for late payments. Add a note to all of your invoices to say that you have the right to charge for late payments. Send a new invoice with your late payment charge after a defined period — say, 14 days after the due date.

With all of the tips, it makes sense to get invoicing terms defined in your client contract before you start working. This will protect you legally from any payment problems.

Were these tips useful? Let me know in the comments below!

Want to get freelancing tips from me? (no more than 1 e-mail a week, I promise!)


Photo credit: “Cash flow” by Jayson Ignacio via Flickr

Give yourself more time by automating your freelancing business

Gemini XII

The idea behind automation is to reduce the amount of human-interaction required to perform certain tasks. When you are freelancing, you commonly have some tasks that you repeat over and over again. These tasks are not necessarily directly related to client work — that is, clients are not paying you to perform these tasks. In other words, you are effectively getting paid $0 per hour for these tasks. Therefore, it makes sense to reduce the amount of time you are spending on them.

What kind of tasks could you automate? Here are a few ideas:

  • Invoice generation
  • Chasing late payments
  • Accountancy
  • Sales pipeline management
  • Performing due dilligence on prospects
  • Lead generation

One way of automating processes is by using a framework. The framework described below can help you automate your own systems.

Framework for automation

1. Document

The starting point for any automation is writing down exactly what steps you take to perform the task. Do it in parallel with the task itself. It will take twice as long, but you have a starting point for automation. I find a Wiki handy for recording these kind of details.

2. Refine

Next time you need to perform the task, revisit your document and follow your own instructions rather than doing it from memory. Are the instructions complete? If not, then you need to revise and refine the documentation. Add descriptive details. Add screenshots to clarify.

3. Reduce friction

Once you have your documented process, take a look through and ask yourself if it is the most efficient way of completing the task. Are there any steps that could be condensed or removed completely?

4. Checklist

The ideal form of documented process is a checklist. Even at this stage, whilst not fully automated, you are likely to save yourself time. Following a checklist, even if you think you know the process well, is going to reduce the amount of mistakes that you make. (Side note: If this seems surprising, I recommend reading The Checklist Manifesto by Atul Gawande. There’s some great stories in there about how simple checklists have helped businesses become more efficient).

5. Review

Be honest, can somebody else perform this task? Does it have to be you? Could someone that had never completed the task before use your instructions? Add or remove any details necessary for this to happen.

6. Automate

At this point, you have a checklist documenting your process. Already you have created a valuable asset for your freelancing business, but you can take it a step further. You don’t have to perform this task ever again, if

a) there is software that can do it for you OR
b) you outsource the process to somebody else

Look for software that could complete the steps in your checklist. Even if you found software that could complete a few steps of the whole process, then that is still a valuable time saver.

A few ideas of starting points:

  • FreeAgent – Invoicing and accounting software for freelancer’s
  • Base CRM – Manage your sales pipeline
  • If This, Then That – create “recipes” using different online sources to perform actions.

Alternatively, how about hiring somebody to do the work? An accountant? Or a more general virtual assistant?

As you create your automated systems, you’ll have more time to focus on what’s important to you.

Was this guide useful? Let me know in the comments below!

Want to get freelancing tips from me? (no more than 1 e-mail a week, I promise!)


photo credit: Gemini XII by Erik Charlton on Flickr

Who is your ideal client?

Odd one out by Kevin Pack on Flickr

“Where can I find more clients?” is one of the most common questions I hear from other freelancers. It’s an almost impossible question to answer.

I find that a good response to this question, is another question: “Who is your ideal client?”.

Why?

Defining an ideal client profile is helpful because it means you are thinking about real people rather than some nebulous concept of “a client”.

Considering your ideal client can be quite simple. Ask yourself questions like:

  • “Do they live in a particular location?”
  • “What kind of business are they involved in?”
  • “How old are they?”
  • “What interests do they have?”
  • “What characteristics do they have?”

As you start to answer these questions, try to visualize the person too.

As you do this, you’ll find yourself building different types of clients that you prefer to work with.

As an example, here are some mine:

  • Directors of digital agencies based in major cities
  • Small business owners that have been established for at least 3 years
  • Entrepreneurs launching SaaS products.
  • People that have an interest in music or sports

By being more specific about your clients, “Where can I find more clients” has now become “Where do I find this person?” which is a much easier question to answer.

For example, let’s say you have an interest in sports. You would like your client to have some kind of investment in this area, as you would rather be working on something you have a passion for. So where might you find clients that are involved with sport? Now it becomes a lot easier. You may think about reaching out to:

  • Gyms or fitness centres
  • Professional sports clubs
  • Sports equipment retailers
  • etc

Once you have your ideal client profile defined, it’s important to say “no” to clients that don’t fit your profile. It’s difficult to say no, and turn down work, but ultimately worthwhile. Clients that don’t meet your ideal profile are going to be difficult to work with.

My own types of ideal clients have helped me decide which projects to take on in the past.

Do you have an ideal client or need help defining one? Let me know in the comments section below!

Want to get freelancing tips from me? (no more than 1 e-mail a week, I promise!)


photo credit: Odd one out by Kevin Pack on flickr

My freelancing goals for 2014

Soccer Goal

In this post, I wanted to summarise some of my freelancing goals for 2014. I hope that by doing so, I’ll hold myself accountable for growing my business next year.

Scale up

When I take on freelancing engagements, clients are currently getting just me. This is fine, but limits the amount of projects I can take on at one time. In 2014, I want this to change so that I can provide more value to clients and take on additional work — I don’t want to be bound by my own time.

I want to grow my business out so that it’s not just me, but a combination of me and and other (freelance) developers. In other words, transition from “Glen The Freelancer” to “Glen the Freelance Business Owner”. I’ve already taken first steps with this one by forming my own company (Yellow Square).

Action: Outsource and manage other developers on future projects.

Enhance my product portfolio

Selling products was one of my failed goals of 2013. My existing WordPress theme aggregator has stagnated after a long period of neglect, and my e-book on freelance development is only 25% complete. I want to put more effort into both of these, and also look into other forms of recurring revenue.

Action: Complete e-book

Read more business books

I’m a slow, but avid reader of books (I’m getting faster — “10 Days To Faster Reading” is helping me with this). Next year I want to be reading more business books and applying the advice to help my freelancing career.

Some great books I’ve read this year and can highly recommend include “E-Myth Revisited”, “Book Yourself Solid” and “Winning Without Losing”.

Action: Read at least 1 business book each month

Teach more

I blog occassionally. I send out mails to my mailing lists occasionally. But I want to do this more, and do it more consistently. I want to help people, and in the process grow my audience.

Action: Blog at least once per month. Send out a mail to my freelancing and software development lists at least once a month.

What plans do you have for next year? Comment at the bottom of this page and let me know, I’d love to hear from you.

Want to get freelancing tips from me? (no more than 1 e-mail a week, I promise!)


photo credit: soccer goal by see-ming lee on flickr

How to avoid time wasters when selling on eBay

I recently tried to sell my old MacBook on eBay, but the winning bidder had zero feedback and subsequently refused to pay. This was annoying, and it was only after this happened that I discovered eBay has some mechanisms to stop this kind of thing happening — but they are disabled by default.

So, you really should enable these options if you want to prevent time wasters and scammers from bidding on your items. You can access the options, called “Buyer Requirements”, by doing the following:

  • Login to eBay
  • Go to your Account Settings page
  • Click on Site Preferences in the left-hand menu
  • Under “Buyer requirements” click “Show” and then “Edit”

Here are the options I recommend:

  1. Block buyers who don’t have a PayPal account.
  2. Block bidders and buyers who have 2 unpaid item(s) recorded on their accounts within 1 month(s)
  3. Block buyers whose primary delivery address is in a location I don’t post to.
  4. Block buyers who have 4 breach of policy report(s) within 1 month(s)
  5. Block buyers who have a Feedback score of -1 or lower
  6. Block buyers who do not have a credit card on file. (Only apply this block to buyers who have a Feedback score of or lower.)
  7. Don’t allow blocked buyers to contact me.

Buyer requirements recommended settings for eBay sellers

The Best Investments I’ve made in my Freelancing Business

Computer being delivered to Norwich City Council, 1957

At the beginning of the year, I vowed to invest resources in order to grow my freelancing business. Here is a list of the most successful in terms of return on investment.

“Recurring Revenue for Consultants” Bootcamp

Cost: $1,400

Hosted by Brennan Dunn and Patrick McKenzie, this contained around 6 hours of fabulous advice from two recognised experts in the field. I’ve wanted to diversify my income so that I was not so reliant on one-off client engagements. This bootcamp has helped to shape my product and service plans for the next year and inspired me to launch FreelanceDevLeads.

Link: Recurring Revenue for Consultants

CopyHackers “The Great Value Proposition Test”

Cost: $48.99

Any of the other CopyHackers books are worth owning, but I found this one particularly valuable. It helps you answer the question “how do you differentiate yourself from your competitors?”

Written in a clear, friendly style, it takes quite a dry subject and makes it compelling by focusing on real-life examples. It can be applied as much to products as it can to your own freelancing business.

Link: The Great Value Proposition Test e-book

FreeAgent

Cost: £150

FreeAgent makes accounting almost fun. At a general level, it has enabled me to keep an eye on my cash flow and make invoicing clients hassle-free.

Link: FreeAgent

Freelancer’s Weekly

Cost: Free

Great actionable advice from freelancing guru Brennan Dunn, someone who has been there and done it (and also written several books about it). More value-per-email than any other list that I’m subscribed to.

Link: Freelancer’s Weekly

Virtual Assistant

Cost: £1,000

This year I’ve worked hard to document the different systems and processes within my business, so outsourcing some of these tasks was the next step. I use my VA for tasks such as research, lead generation and data entry.

PCG Membership

Cost: £120

Joining a professional organisation such as PCG is worthwhile to have support from other like-minded individuals. One of the perks of joining was a free consulting contract template. Considering the cost of lawyers, this was worth the price of membership alone.

Link: PCG

E-Myth Revisited

Cost: £6.67

This book really sold me on the idea of creating systems within my business to make it more valuable. If you take yourself out of the equation, your freelancing business is unlikely to be worth much unless you have some repeatable processes in place. (Oh, and try to ignore the cringe-worthy “Sarah’s Pies” anecdotes.)

Link: E-Myth Revisited on Amazon

I’d love to hear about your own successful investments. Add a comment below, or send me an e-mail.

Want to get freelancing tips from me? (no more than 1 e-mail a week, I promise!)


Making the leap to freelancing

Leap of faith by kodomut, from Flickr

Being my own boss was always a dream of mine, but it took two life-changing events for it to become a reality. Being made redundant from my job and the imminent birth of my first son meant I had a big decision to make. Should I look for another permanent position somewhere, or should I start out on my own?

“If you don’t build your dream someone will hire you to help build theirs.” — Tony A. Gaskins Jr.

I bit the bullet, and I have not looked back.

In this article, I’m going to highlight three of the most important aspects to consider when starting out as a freelance developer: setting goals, embracing the business mindset and finding work.

Motivation for going solo

For anyone considering going freelance, it’s important to set your own motivation and goals. When times are tough – and you will most certainly have downs as well as ups – these goals can help keep you on the right track. My priorities were:

  1. Maximising time spent with my family
  2. Be able to work remotely
  3. Work outside “normal” 9-5 hours
  4. Being able to cherry-pick projects of interest
  5. Having the ultimate decision in choosing technologies for projects

The word “freedom” could be applied to all of these. It’s the underlying motivation that drives me.

It was pretty clear from day one that just relying on my software development skills was not going to be enough to cut it out in the big wide world. I realised that I would need to juggle three quite different roles:

  1. Technician
  2. Marketer
  3. Salesperson

Getting into the business frame of mind can help you add marketing and sales skills to your repertoire.

You are a business as well as a freelancer

Keep in mind from the start that your are business rather than “just” a freelancer. Even if you are the only person involved, you are still a business and you should be running your freelancing operation as one. This means getting the balance between the three roles right. By just focusing on your craft, you’ll soon find your leads drying up.

A few books I can recommend to help you learn about these different roles:

  1. E-Myth Revisited (Michael E. Gerber, 1994)
  2. Winning Without Losing (Martin Bjergegaard and Jordan Milne, 2013)
  3. 4-Hour Work Week (Timothy Ferriss, 2011)
  4. Book Yourself Solid (Michael Port, 2011)

Finding work

I recently surveyed a few fellow freelancer’s about how they secured their first paying gig.

The two most common answers were a) going back to existing employers and b) referrals

Existing employers

Initially, this might seem a strange option — why would you freelance for a company that you used to work for? Many reasons…

Companies are increasingly looking to take on freelancers, rather than permanent employees, for one-off projects. It’s worth getting in touch with your existing employer(s) and seeing if there are any projects they would like to contract out. By approaching people you’ve worked with before, the level of trust is already there — there is no need to prove yourself again. This also means it’s less of a risk for the company you are approaching.

Referrals

Having a good reputation for what you do is essential. If you are good at your job, then people are likely to refer business onto you. For this to work you need to make sure that people know that you are freelancing, and actively seeking work. A simple Tweet to let people know your availability could be all that it takes for somebody to think “ah-ha, I know somebody that is looking for a web developer at the moment”.

However, there are many other ways of getting work. Pick one and focus on it rather than spreading yourself too thinly. Any of these methods can be fruitful if you put the effort in.

  • Job Boards
  • Local networking events
  • Social sites such as LinkedIn

Summing up

A couple of years down the line, I am still working as a freelance developer and own my own software business. I can’t imagine ever going back to a daily 9-5 office job, and would recommend going solo to anyone. It’s allowed me to spend lots of time with my family, work with companies all around the world and even when I’ve been without work – which on occasion has lasted several weeks – something new and interesting has always turned up.

photo credit: Leap of faith by kodomut, from Flickr

Getting your first freelance development client

One of the most frequent questions I get from people after I have told them I’m a freelancer is how did you find work at the beginning?.

In the research for my book, I asked that very question to 50 other freelance developers and the results were interesting. Two particular methods stood as as the most popular options for getting initial clients.

Source of first freelancing client

Let’s consider these two most popular options a little.

Existing employers

Initially, this might seem a strange option — why would you freelance for a company that you used to work for? Many reasons…

Companies are increasingly looking to take on freelancers, rather than permanent employees, for one-off projects. It’s worth getting in touch with your existing employer(s) and seeing if there are any projects they would like to farm out. By approaching people you’ve worked with before, you know the level of trust is already there — there is no need to prove yourself again. This also means it’s less risk for the company you are approaching.

Referrals

Having a good reputation at what you do is essential. If you are good at your job, then people are likely to refer business onto you. For this to work you need to make sure that people know that you are freelancing, and actively seeking work. A simple Tweet to let people know your availability could be all that it takes for somebody to think “ah-ha, I know somebody that is looking for a web developer at the moment”.

Want to get more information on how to get freelance clients? My book goes into this in more detail, so sign up to be notified when it is available.