Verifying an API Key

If a print service provider has provided users of the printer driver with API keys, the Workflow process that receives print jobs will need to verify the API key. This topic shows how to do that.

The API key in the HTTP headers

If the printer driver was configured with an API key, it will include the API key in its HTTP headers as a bearer token when sending a print job. Bearer token authorization looks like this:
Authorization: Bearer «token»
where «token» will be the API key.

The Workflow process

The Workflow process will begin with a Server Input task.

In order to tell the printer driver if an API key is missing or incorrect, the Input task of the process must be set to return a custom HTTP server response code, which is stored in a variable (in this example: %{http_response}).

Retrieving the API key from the HTTP headers can be done with a Run Script task. For example:

// Get Bearer Key from raw header

var rawHeaders = Watch.ExpandString("xmlget('/request[1]/header[1]/rawheaders[1]',Value,KeepCase,NoTrim)");

var authHeaderPattern = /^Authorization=Bearer (\S+)$/m;

var matchResult = rawHeaders.match(authHeaderPattern);

if (matchResult != null && matchResult.length == 2) {

Watch.SetVariable ('bearer_key', matchResult[1]);

Watch.SetVariable ('key_found', 'yes');

} else {

Watch.SetVariable ('bearer_key', '');

Watch.SetVariable ('key_found', 'no');

}

Watch.log('*'+Watch.GetVariable('bearer_key').length+'*', 2);

A following Text Condition task can check if the API key was found (here: the %{key_found} variable is equal to yes).

Another Text Condition task checks if the API key is actually valid (here: comparing the value found in the %{bearer_key} variable to a string value).
If it is valid, the job may be processed by the Job Processor task.

If the API key wasn't valid, use the Set Job Infos and Variables task to assign the value of the respective response code, 401, to the variable that was selected in the Input task.

If the API key is missing, the code should be 400 (bad request).