Plugin Updates: Securing Download Links

Ever since the release of the Plugin Update Checker library, one of the most common questions asked has been this: “How can I secure my download links so that only users who have purchased my plugin can download an update?”

In this post I’ll try to answer that question in the context of using WP Update Server to serve plugin updates. I will also provide a couple of practical examples from one of my commercial plugins.

Lets get started. There are many ways to secure update downloads, but most of them boil down to this:

  1. Give some kind of security token to each user. This could be a login + password to a membership site, a license key, or something more esoteric.
  2. Whenever someone installs your plugin on their site, ask them to enter the key/log in/whatever.
  3. Modify the plugin to append the token to each update request.
  4. Write a server script that verifies the token before it allows download.

Choose a Security Token

How you implement the first two steps will vary greatly depending on your plugin UI and what online store, cart software, or membership plugin you use. You might already have some kind of customer authentication mechanism in place that just needs a bit of tweaking to be used for updates, or you might need to build your own from scratch. There’s no “one size fits all” solution here.

Personally, I prefer to use license keys. Whenever someone buys my Admin Menu Editor Pro plugin, the order processing script generates a random key, stores it in the database, and sends the key and a download link to the customer’s email. Then, when they install the plugin, there’s a link to enter the license key.

I won’t include the license management code here because it’s beyond the scope of this post and built for that specific plugin, but the user interface looks something like this (click to enlarge):

Admin Menu Editor Pro entry on the "Plugins" page

Add the Token To Update Requests

Now, how do we add our security token to each update request? You can do that by using the addQueryArgFilter($callback) method of the update checker. The callback function will receive an associative array of query arguments. Just add the token to the list and return the modified array.

Here’s an example:

/* ... Code that initializes the update checker ... */

//Add the license key to query arguments.
$updateChecker->addQueryArgFilter('wsh_filter_update_checks');
public function wsh_filter_update_checks($queryArgs) {
	$settings = get_option('my_plugin_settings');
	if ( !empty($settings['license_key']) ) {
		$queryArgs['license_key'] = $settings['license_key'];
	}
	return $queryArgs;
}

Use the Token To Authorize Downloads

Finally, let’s make the update server verify the security token before it lets the user download an update. To do that, you’ll need to create a custom server class (see Extending the server) and override at least the Wpup_UpdateServer::checkAuthorization($request) method. Here’s what you should do in this method:

  1. Retrieve the query argument(s) that contains the token by using $request->param('arg_name').
  2. Verify the token. Again, this part is up to you. You could look it up in a database, use a checksum to validate it, or something else.
  3. If the token is good, you don’t need to do anything special.
  4. If the token is invalid, call $this->exitWithError('Error message') to output an error and stop script execution.

Below is a simplified version of the script I use to implement secure updates for  Admin Menu Editor Pro. It is slightly more advanced than the above outline, but the general idea is the same.

(Again, license management is beyond the scope of this post, so I’ve omitted most of the code that deals with loading and validating licenses. Just treat verifyLicenseExists() and other licensing functions as pseudo-code.)

class SecureUpdateServer extends Wpup_UpdateServer {
	protected $licenseServer;

	public function __construct($serverUrl, $licenseServer) {
		parent::__construct($serverUrl);
		$this->licenseServer = $licenseServer;
	}

	protected function initRequest($query) {
		$request = parent::initRequest($query);

		//Load the license, if any.
		$license = null;
		if ( $request->param('license_key') ) {
			$result = $this->licenseServer->verifyLicenseExists(
				$request->slug,
				$request->param('license_key')
			);
			if ( is_wp_error($result) ) {
				//If the license doesn't exist, we'll output an invalid dummy license.
				$license = new Wslm_ProductLicense(array(
					'status' => $result->get_error_code(),
					'error' => array(
						'code' => $result->get_error_code(),
						'message' => $result->get_error_message(),
					),
				));
			} else {
				$license = $result;
			}
		}

		$request->license = $license;
		return $request;
	}

	protected function filterMetadata($meta, $request) {
		$meta = parent::filterMetadata($meta, $request);

		//Include license information in the update metadata. This saves an HTTP request
		//or two since the plugin doesn't need to explicitly fetch license details.
		$license = $request->license;
		if ( $license !== null ) {
			$meta['license'] = $this->licenseServer->prepareLicenseForOutput($license);
		}

		//Only include the download URL if the license is valid.
		if ( $license && $license->isValid() ) {
			//Append the license key or to the download URL.
			$args = array( 'license_key' => $request->param('license_key') );
			$meta['download_url'] = self::addQueryArg($args, $meta['download_url']);
		} else {
			//No license = no download link.
			unset($meta['download_url']);
		}

		return $meta;
	}

	protected function checkAuthorization($request) {
		parent::checkAuthorization($request);

		//Prevent download if the user doesn't have a valid license.
		$license = $request->license;
		if ( $request->action === 'download' && ! ($license && $license->isValid()) ) {
			if ( !isset($license) ) {
				$message = 'You must provide a license key to download this plugin.';
			} else {
				$error = $license->get('error');
				$message = isset($error) ? $error : 'Sorry, your license is not valid.';
			}
			$this->exitWithError($message, 403);
		}
	}
}

If you have any questions, feel free to leave a comment.

Related posts :

6 Responses to “Plugin Updates: Securing Download Links”

  1. Robert says:

    finally got it – no need to answer my last comment ;-)

  2. Janek says:

    I’ve been using your libraries for theme and plugin auto updates. Both of them are simple to implement and work great. I’m looking forward to implementing the WP Update Server.

  3. Erwin says:

    Hi, is there a tutorial how to do this? My PHP knowledge is not good enough to fix this. Or can you help me to fix this? I have no idea how to start. I use your Plugin Update Checker with the WP Update Server and that work awesome.

  4. Jānis Elsts says:

    There’s no other tutorial other than what you see on this page. Everyone has different ideas about how they want to protect their download links – username/password, subscriptions, license keys, or something else – so it’s not really possible to write a general-purpose tutorial. I’m afraid you’ll have to figure out most of it yourself :)

  5. Erwin says:

    I like the way you use with a license key, but thnx I try to figure it out.

  6. joseph says:

    your libs are very straightforward. thanks

Leave a Reply