Prevent API request if authkey is not set and print error if API host is not set.

The authentication key may be derived from a saved property file or from the command line as an optional argument to override the property file.
But if the property file does not exist, and the command line override is not set, then the API request is made and fails with "authentication
required".

This commit factors all the authenticated commands so that there is a single point where the authentication argument is added to a command or sub-command.
It is more convenient then to make the auth key a required positional argument. This is not done at this point however as it will require some changes to the
unit tests.

This commit also includes a fix for issue #29. If default.props does not exist because CLI was not built, then CLI should still be usable if user provides an API host override. Hence, allow for missing default properties file but raise an error if trying to do any operation against the API.
diff --git a/tools/cli/wsk b/tools/cli/wsk
index 1eeec4e..03dbfde 100755
--- a/tools/cli/wsk
+++ b/tools/cli/wsk
@@ -40,13 +40,17 @@
 from wskpackage import Package
 from wsknamespace import Namespace
 from wsksdk import Sdk
-from wskutil import apiBase, chooseFromArray, resolveNamespace, request, responseError
+from wskutil import addAuthenticatedCommand, apiBase, chooseFromArray, resolveNamespace, request, responseError
 
 def main():
-    userpropsLocation = os.getenv("WSK_CONFIG_FILE", '%s/.wskprops' % os.path.expanduser('~'))
+    userpropsLocation = os.getenv('WSK_CONFIG_FILE', '%s/.wskprops' % os.path.expanduser('~'))
     userprops = wskprop.importPropsIfAvailable(userpropsLocation)
     whiskprops = wskprop.importDefaultProps()
 
+    # if the default properties failed to load (because file does not exist) then create a stub
+    if whiskprops is None:
+        whiskprops = { 'CLI_API_HOST': None, 'WHISK_VERSION_DATE': None }
+
     exitCode = 0
     try:
         args = parseArgs(userprops)
@@ -54,7 +58,7 @@
         apiversion = resolveOverrides('v1', userprops.get('APIVERSION'), args.apiversionOverride)
 
         props = {
-            'apihost' : '%s:443' % apihost,
+            'apihost' : apihost,
             'apiversion': apiversion,
             'namespace': resolveNamespace(userprops, 'NAMESPACE'),
             'clibuild' : whiskprops['WHISK_VERSION_DATE']
@@ -62,6 +66,10 @@
 
         if (args.verbose):
             print props
+        if apihost is None and (args.cmd != 'property' or args.cmd == 'property' and args.subcmd != 'get'):
+            print 'error: API host is not set. Set it with "wsk property set --apihost <host>".'
+            return 2
+
         exitCode = {
          'list'         : Namespace().listEntitiesInNamespace,
          'action'       : Action().cmd,
@@ -126,7 +134,7 @@
 
     listmenu = subparsers.add_parser('list', help='list all triggers, actions, and rules in the registry')
     listmenu.add_argument('name', nargs='?', help='the namespace to list')
-    listmenu.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+    addAuthenticatedCommand(listmenu, props)
 
     if argcomplete:
         argcomplete.autocomplete(parser)
@@ -135,7 +143,7 @@
 def propCmd(args, props, userprops, propsLocation):
     if args.subcmd == 'set':
         if args.verbose:
-            print "ok: whisk property file %s" % propsLocation
+            print 'ok: whisk property file %s' % propsLocation
         if args.auth:
             wskprop.updateProps('AUTH', args.auth, propsLocation)
             print 'ok: whisk auth set'
@@ -152,7 +160,7 @@
             else:
                 auth = userprops.get('AUTH')
             if auth is None:
-                print "error: cannot set namespace without an authentication key"
+                print 'error: cannot set namespace without an authentication key'
                 return 1
             res = request('GET', url, auth=auth, verbose=args.verbose)
             namespaces = None
@@ -169,7 +177,7 @@
                         return 0
                     elif choice != None:
                         wskprop.updateProps('NAMESPACE', '%s' % choice, propsLocation)
-                        print "ok: namespace set to %s" % choice
+                        print 'ok: namespace set to %s' % choice
                         return 0
                 print 'error: you are either not entitled to a namespace or you made an invalid choice'
                 return 1
@@ -178,7 +186,7 @@
         return 0
     if args.subcmd == 'unset':
         if args.verbose:
-            print "ok: whisk property file %s" % propsLocation
+            print 'ok: whisk property file %s' % propsLocation
         if args.auth:
             wskprop.updateProps('AUTH', '', propsLocation)
             print 'ok: whisk auth unset'
@@ -205,18 +213,17 @@
         if args.all or args.cliversion:
             print 'whisk CLI version\t%s' % props['clibuild']
         if args.all or args.apibuild:
-            url = 'https://%(apibase)s' % { 'apibase' : apiBase(props) }
-            res = request('GET', url, verbose=args.verbose)
-            if res.status == httplib.OK:
-                try:
+            if props['apihost'] is not None:
+                url = 'https://%(apibase)s' % { 'apibase' : apiBase(props) }
+                res = request('GET', url, verbose=args.verbose)
+                if res.status == httplib.OK:
                     result = json.loads(res.read())
                     print 'whisk API build\t\t%s' % result['build']
-                except:
-                    print 'whisk API build\t\t%s' % 'unrecognized failure'
-                    return 1
+                else:
+                    print 'whisk API build\t\tCannot determine API build:',
+                    return responseError(res, prefix=None)
             else:
-                print 'whisk API build\t\t',
-                return responseError(res, prefix=None)
+                print 'whisk API build\t\tNone',
         return 0
     return 2
 
diff --git a/tools/cli/wskaction.py b/tools/cli/wskaction.py
index 188ca7b..4bc93de 100644
--- a/tools/cli/wskaction.py
+++ b/tools/cli/wskaction.py
@@ -21,7 +21,7 @@
 import argparse
 import urllib
 from wskitem import Item
-from wskutil import bold, request, getParams, getActivationArgument, getAnnotations, responseError, parseQName, getQName, apiBase, getPrettyJson
+from wskutil import addAuthenticatedCommand, bold, request, getParams, getActivationArgument, getAnnotations, responseError, parseQName, getQName, apiBase, getPrettyJson
 
 #
 # 'wsk actions' CLI
@@ -35,6 +35,7 @@
         subcmd = parser.add_parser('create', help='create new action')
         subcmd.add_argument('name', help='the name of the action')
         subcmd.add_argument('artifact', help='artifact (e.g., file name) containing action definition')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--docker', help='treat artifact as docker image path on dockerhub', action='store_true')
         subcmd.add_argument('--copy', help='treat artifact as the name of an existing action', action='store_true')
         subcmd.add_argument('--sequence', help='treat artifact as comma separated sequence of actions to invoke', action='store_true')
@@ -44,11 +45,11 @@
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
         subcmd.add_argument('-t', '--timeout', help='the timeout limit in milliseconds when the action will be terminated', type=int)
         subcmd.add_argument('-m', '--memory', help='the memory limit in MB of the container that runs the action', type=int)
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('update', help='update an existing action')
         subcmd.add_argument('name', help='the name of the action')
         subcmd.add_argument('artifact', nargs='?', default=None, help='artifact (e.g., file name) containing action definition')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--docker', help='treat artifact as docker image path on dockerhub', action='store_true')
         subcmd.add_argument('--copy', help='treat artifact as the name of an existing action', action='store_true')
         subcmd.add_argument('--sequence', help='treat artifact as comma separated sequence of actions to invoke', action='store_true')
@@ -58,13 +59,12 @@
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
         subcmd.add_argument('-t', '--timeout', help='the timeout limit in milliseconds when the action will be terminated', type=int)
         subcmd.add_argument('-m', '--memory', help='the memory limit in MB of the container that runs the action', type=int)
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('invoke', help='invoke action')
         subcmd.add_argument('name', help='the name of the action to invoke')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-p', '--param', help='parameters', nargs=2, action='append')
         subcmd.add_argument('-b', '--blocking', action='store_true', help='blocking invoke')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
         subcmd.add_argument('-r', '--result', help='show only activation result if a blocking activation (unless there is a failure)', action='store_true')
 
         self.addDefaultCommands(parser, props)
@@ -85,7 +85,7 @@
             actions = [ getQName(a, ns) for a in actions ]
             args.param.append([ '_actions', json.dumps(actions)])
         
-        validExe = exe is not None and "kind" in exe
+        validExe = exe is not None and 'kind' in exe
         if update or validExe: # if create action, then exe must be valid
             payload = {}
             if args.annotation:
@@ -158,7 +158,7 @@
     def getExec(self, args, props):
         exe = {}
         if args.docker:
-            exe['kind'] = "blackbox"
+            exe['kind'] = 'blackbox'
             exe['image'] = args.artifact
         elif args.copy:
             existingAction = args.artifact
@@ -169,10 +169,10 @@
         elif args.artifact is not None and os.path.isfile(args.artifact):
             contents = open(args.artifact, 'rb').read()
             if args.artifact.endswith('.swift'):
-                exe['kind'] = "swift"
+                exe['kind'] = 'swift'
                 exe['code'] = contents
             else:
-                exe['kind'] = "nodejs"
+                exe['kind'] = 'nodejs'
                 exe['code'] = contents
         if args.lib:
             exe['initializer'] = base64.b64encode(args.lib.read())
diff --git a/tools/cli/wskactivation.py b/tools/cli/wskactivation.py
index 247dc75..791959c 100644
--- a/tools/cli/wskactivation.py
+++ b/tools/cli/wskactivation.py
@@ -21,7 +21,7 @@
 from datetime import datetime, timedelta
 import copy
 from wskitem import Item
-from wskutil import apiBase, bold, parseQName, getQName, request, responseError, getPrettyJson
+from wskutil import addAuthenticatedCommand, apiBase, bold, parseQName, getQName, request, responseError, getPrettyJson
 
 # how many seconds to sleep between polls
 SLEEP_SECONDS = 2
@@ -39,12 +39,12 @@
 class Activation(Item):
 
     def __init__(self):
-        super(Activation, self).__init__("activation", "activations")
+        super(Activation, self).__init__('activation', 'activations')
 
     def getItemSpecificCommands(self, parser, props):
         subcmd = parser.add_parser('list', help='retrieve activations')
         subcmd.add_argument('name', nargs='?', help='the namespace or action to list')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-s', '--skip', help='skip this many entities from the head of the collection', type=int, default=0)
         subcmd.add_argument('-l', '--limit', help='only return this many entities from the collection', type=int, default=30)
         subcmd.add_argument('-f', '--full', help='return full documents for each activation', action='store_true')
@@ -54,22 +54,22 @@
         subcmd = parser.add_parser('get', help='get %s' % self.name)
         subcmd.add_argument('name', help='the name of the %s' % self.name)
         subcmd.add_argument('project', nargs='?', help='project only this property')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-s', '--summary', help='summarize entity details', action='store_true')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('logs', help='get the logs of an activation')
         subcmd.add_argument('id', help='the activation id')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-s', '--strip', help='strip timestamp and stream information', action='store_true')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd= parser.add_parser('result', help='get the result of an activation')
         subcmd.add_argument('id', help='the invocation id')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
         # poll
         subcmd= parser.add_parser('poll', help='poll continuously for log messages from currently running actions')
         subcmd.add_argument('name', nargs='?', help='the namespace to poll')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-e', '--exit', help='exit after this many seconds', type=int, default=-1)
         subcmd.add_argument('-ss', '--since-seconds', help='start polling for activations this many seconds ago', type=long, default=0, dest='since_secs')
         subcmd.add_argument('-sm', '--since-minutes', help='start polling for activations this many minutes ago', type=long, default=0, dest='since_mins')
@@ -109,12 +109,12 @@
         res = self.listCmd(args, props)
         if res.status == httplib.OK:
             result = json.loads(res.read())
-            print bold("activations")
+            print bold('activations')
             for a in result:
                 if args.full:
                     print getPrettyJson(a)
                 else:
-                    print "{:<45}{:<40}".format(a['activationId'], a['name'])
+                    print '{:<45}{:<40}'.format(a['activationId'], a['name'])
             return 0
         else:
             return responseError(res)
@@ -122,7 +122,6 @@
     def getEntitySummary(self, entity):
         kind = self.name
         fullName = getQName(entity['name'], entity['namespace'])
-        id = entity['activationId']
         end = datetime.fromtimestamp(entity['end'] / 1000)
         status = entity['response']['status']
         result = getPrettyJson(entity['response']['result'])
@@ -174,11 +173,11 @@
     def poll(self, args, props):
         name = args.name if args.name else '/_'
         args.name = getQName(name, '_') # kludge: use default namespace unless explicitly specified
-        print "Hit Ctrl-C to exit."
+        print 'Hit Ctrl-C to exit.'
         try: 
             self.console(args, props)
         except KeyboardInterrupt:
-            print ""
+            print ''
 
     # return the result of a 'wsk activation list' call, an HTTPResponse
     def listCmd(self, args, props):
@@ -282,7 +281,7 @@
 # Extract the timestamp from an activation, or return 0
 #
 def extractTimestamp(activation):
-    return activation["start"]
+    return activation['start']
 
 #
 # Print all the logs for an activation record
@@ -291,15 +290,15 @@
 #
 def printLogsForActivation(activation):
     global lastTime
-    print 'Activation: %s (%s)' % (activation["name"], activation["activationId"])
+    print 'Activation: %s (%s)' % (activation['name'], activation['activationId'])
 
-    if "logs" in activation:
-        for element in activation["logs"]:
+    if 'logs' in activation:
+        for element in activation['logs']:
             print element
         # update the lastTime global timestamp if necessary to record the latest
         # start time yet fetched
-        if activation["start"] > lastTime:
-            lastTime = activation["start"]
+        if activation['start'] > lastTime:
+            lastTime = activation['start']
 #
 # Print all the logs for a list of activation records
 # 
@@ -308,8 +307,8 @@
 #
 def printLogs(L, reported):
     for a in L:
-        if not a["activationId"] in reported:
-            reported.add(a["activationId"])
+        if not a['activationId'] in reported:
+            reported.add(a['activationId'])
             printLogsForActivation(a)
 
 #
diff --git a/tools/cli/wskitem.py b/tools/cli/wskitem.py
index cbd49a7..933f159 100644
--- a/tools/cli/wskitem.py
+++ b/tools/cli/wskitem.py
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-from wskutil import apiBase, bold, request, responseError, parseQName, getQName, getPrettyJson, getParameterNamesFromAnnotations, getDescriptionFromAnnotations
+from wskutil import addAuthenticatedCommand, apiBase, bold, request, responseError, parseQName, getQName, getPrettyJson, getParameterNamesFromAnnotations, getDescriptionFromAnnotations
 import urllib
 import abc
 import json
@@ -48,18 +48,18 @@
             subcmd = subcmds.add_parser('get', help='get %s' % self.name)
             subcmd.add_argument('name', help='the name of the %s' % self.name)
             subcmd.add_argument('project', nargs='?', help='project only this property')
+            addAuthenticatedCommand(subcmd, props)
             subcmd.add_argument('-s', '--summary', help='summarize entity details', action='store_true')
-            subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         if ('delete' in which):
             subcmd = subcmds.add_parser('delete', help='delete %s' % self.name)
             subcmd.add_argument('name', help='the name of the %s' % self.name)
-            subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+            addAuthenticatedCommand(subcmd, props)
 
         if ('list' in which):
             subcmd = subcmds.add_parser('list', help='list all %s' % self.collection)
             subcmd.add_argument('name', nargs='?', help='the namespace to list')
-            subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+            addAuthenticatedCommand(subcmd, props)
             subcmd.add_argument('-s', '--skip', help='skip this many entities from the head of the collection', type=int, default=0)
             subcmd.add_argument('-l', '--limit', help='only return this many entities from the collection', type=int, default=30)
 
diff --git a/tools/cli/wsknamespace.py b/tools/cli/wsknamespace.py
index 20c94de..cba1704 100644
--- a/tools/cli/wsknamespace.py
+++ b/tools/cli/wsknamespace.py
@@ -21,7 +21,7 @@
 from wsktrigger import Trigger
 from wskrule import Rule
 from wskpackage import Package
-from wskutil import apiBase, bold, parseQName, request, responseError
+from wskutil import addAuthenticatedCommand, apiBase, bold, parseQName, request, responseError
 
 #
 # 'wsk namespaces' CLI
@@ -34,11 +34,11 @@
         subcmds = commands.add_subparsers(title='available commands', dest='subcmd')
 
         subcmd = subcmds.add_parser('list', help='list available namespaces')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
         subcmd = subcmds.add_parser('get', help='get entities in namespace')
         subcmd.add_argument('name', nargs='?', help='the namespace to list')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
     def cmd(self, args, props):
         if args.subcmd == 'list':
@@ -52,9 +52,9 @@
 
         if res.status == httplib.OK:
             result = json.loads(res.read())
-            print bold("namespaces")
+            print bold('namespaces')
             for n in result:
-                print "{:<25}".format(n)
+                print '{:<25}'.format(n)
             return 0
         else:
             return responseError(res)
diff --git a/tools/cli/wskpackage.py b/tools/cli/wskpackage.py
index f7f7021..e151b13 100644
--- a/tools/cli/wskpackage.py
+++ b/tools/cli/wskpackage.py
@@ -19,7 +19,7 @@
 import sys
 import urllib
 from wskitem import Item
-from wskutil import request, getParams, getAnnotations, responseError, parseQName, getQName, hilite, apiBase
+from wskutil import addAuthenticatedCommand, request, getParams, getAnnotations, responseError, parseQName, getQName, hilite, apiBase
 
 #
 # 'wsk packages' CLI
@@ -27,33 +27,33 @@
 class Package(Item):
 
     def __init__(self):
-        super(Package, self).__init__("package", "packages")
+        super(Package, self).__init__('package', 'packages')
 
     def getItemSpecificCommands(self, parser, props):
         subcmd = parser.add_parser('create', help='create a new package')
         subcmd.add_argument('name', help='the name of the package')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-a', '--annotation', help='annotations', nargs=2, action='append')
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('update', help='create a new package')
         subcmd.add_argument('name', help='the name of the package')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-a', '--annotation', help='annotations', nargs=2, action='append')
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
         
         subcmd = parser.add_parser('bind', help='bind parameters to the package')
         subcmd.add_argument('package', help='the name of the package')
         subcmd.add_argument('name', help='the name of the bound package')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-a', '--annotation', help='annotations', nargs=2, action='append')
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
         
         subcmd = parser.add_parser('refresh', help='refresh package bindings')
         subcmd.add_argument('name', nargs='?', help='the namespace to refresh')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
         
         self.addDefaultCommands(parser, props)
 
@@ -114,27 +114,27 @@
         res = request('POST', url, auth=args.auth, verbose=args.verbose)
         if res.status == httplib.OK:
             result = json.loads(res.read())
-            print "%(namespace)s refreshed successfully!" % {'namespace': args.name}
-            print hilite("created bindings:", True)
+            print '%(namespace)s refreshed successfully!' % {'namespace': args.name}
+            print hilite('created bindings:', True)
             print '\n'.join(result['added'])
-            print hilite("updated bindings:", True)
+            print hilite('updated bindings:', True)
             print '\n'.join(result['updated'])
-            print hilite("deleted bindings:", True)
+            print hilite('deleted bindings:', True)
             print '\n'.join(result['deleted'])
             return 0
         elif res.status == httplib.NOT_IMPLEMENTED:
-            print "error: This feature is not implemented in the targeted deployment"
+            print 'error: This feature is not implemented in the targeted deployment'
             return responseError(res)
         else:
             result = json.loads(res.read())
-            print "error: %(error)s" % {'error': result['error']}
+            print 'error: %(error)s' % {'error': result['error']}
             return responseError(res)
             
         
     def formatListEntity(self, e):
         ns = e['namespace']
         name = getQName(e['name'], ns)
-        return "{:<65} {:<8}{:<7}".format(
+        return '{:<65} {:<8}{:<7}'.format(
                 name,
                 'shared' if (e['publish'] or e['publish'] == 'true') else 'private',
                 'binding' if e['binding'] else '')
diff --git a/tools/cli/wskprop.py b/tools/cli/wskprop.py
index e8d7463..e17add1 100644
--- a/tools/cli/wskprop.py
+++ b/tools/cli/wskprop.py
@@ -64,7 +64,7 @@
         if key != '' and val != '':
             props[key.upper().replace('.','_')] = val
         elif key != '':
-            props[key.upper().replace('.','_')] = ""
+            props[key.upper().replace('.','_')] = ''
     return props
 
 def updateProps(key, value, filename):
@@ -87,7 +87,7 @@
     requiredPropertiesByValue = [ getPropertyValue(key, properties) for key in requiredPropertiesByName ]
     requiredProperties = dict(zip(requiredPropertiesByName, requiredPropertiesByValue))
     invalidProperties = [ key for key in requiredPropertiesByName if requiredProperties[key] == None ]
-    deferredInfo = ""
+    deferredInfo = ''
     for key, value in requiredProperties.items():
         if value == None or value == '':
             print 'property "%s" not found in environment or property file' % key
diff --git a/tools/cli/wskrule.py b/tools/cli/wskrule.py
index 8111998..a23144f 100644
--- a/tools/cli/wskrule.py
+++ b/tools/cli/wskrule.py
@@ -17,46 +17,46 @@
 import json
 import httplib
 from wskitem import Item
-from wskutil import apiBase, parseQName, request, responseError
+from wskutil import addAuthenticatedCommand, apiBase, parseQName, request, responseError
 import urllib
 
 class Rule(Item):
 
     def __init__(self):
-        super(Rule, self).__init__("rule", "rules")
+        super(Rule, self).__init__('rule', 'rules')
 
     def getItemSpecificCommands(self, parser, props):
         subcmd = parser.add_parser('create', help='create new rule')
         subcmd.add_argument('name', help='the name of the rule')
         subcmd.add_argument('trigger', help='the trigger')
         subcmd.add_argument('action', help='the action')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
         subcmd.add_argument('--enable', help='enable rule after creating it', action='store_true', default=False)
 
         subcmd = parser.add_parser('delete', help='delete %s' % self.name)
         subcmd.add_argument('name', help='the name of the %s' % self.name)
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--disable', help='automatically disable rule defore deleting it', action='store_true', default=False)
 
         subcmd = parser.add_parser('update', help='update an existing rule')
         subcmd.add_argument('name', help='the name of the rule')
         subcmd.add_argument('trigger', help='the trigger')
         subcmd.add_argument('action', help='the action')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('enable', help='enable rule')
         subcmd.add_argument('name', help='the name of the rule')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
         subcmd = parser.add_parser('disable', help='disable rule')
         subcmd.add_argument('name', help='the name of the rule')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
         subcmd = parser.add_parser('status', help='get rule status')
         subcmd.add_argument('name', help='the name of the rule')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
+        addAuthenticatedCommand(subcmd, props)
 
         self.addDefaultCommands(parser, props, ['get', 'list'])
 
diff --git a/tools/cli/wsksdk.py b/tools/cli/wsksdk.py
index 81d5053..6e2be47 100644
--- a/tools/cli/wsksdk.py
+++ b/tools/cli/wsksdk.py
@@ -50,7 +50,7 @@
             print 'Unknown SDK component:', args.component
 
     def swiftDownload(self, args, props):
-        print "Swift SDK coming soon"
+        print 'Swift SDK coming soon'
 
     def dockerDownload(self, args, props):
         tarFile = 'blackbox-0.1.0.tar.gz'
diff --git a/tools/cli/wsktrigger.py b/tools/cli/wsktrigger.py
index ec52e09..059a025 100644
--- a/tools/cli/wsktrigger.py
+++ b/tools/cli/wsktrigger.py
@@ -18,35 +18,35 @@
 import httplib
 from wskitem import Item
 from wskaction import Action
-from wskutil import apiBase, dict2obj, getParam, getParams, getActivationArgument, getAnnotations, parseQName, responseError, request, getQName
+from wskutil import addAuthenticatedCommand, apiBase, dict2obj, getParam, getParams, getActivationArgument, getAnnotations, parseQName, responseError, request, getQName
 import urllib
 
 class Trigger(Item):
 
     def __init__(self):
-        super(Trigger, self).__init__("trigger", "triggers")
+        super(Trigger, self).__init__('trigger', 'triggers')
 
     def getItemSpecificCommands(self, parser, props):
         subcmd = parser.add_parser('create', help='create new trigger')
         subcmd.add_argument('name', help='the name of the trigger')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
         subcmd.add_argument('-a', '--annotation', help='annotations', nargs=2, action='append')
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
         subcmd.add_argument('-f', '--feed', help='trigger feed')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('update', help='update an existing trigger')
         subcmd.add_argument('name', help='the name of the trigger')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('--shared', nargs='?', const='yes', choices=['yes', 'no'], help='shared action (default: private)')
         subcmd.add_argument('-a', '--annotation', help='annotations', nargs=2, action='append')
         subcmd.add_argument('-p', '--param', help='default parameters', nargs=2, action='append')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         subcmd = parser.add_parser('fire', help='fire trigger event')
         subcmd.add_argument('name', help='the name of the trigger')
         subcmd.add_argument('payload', help='the payload to attach to the trigger', nargs ='?')
+        addAuthenticatedCommand(subcmd, props)
         subcmd.add_argument('-p', '--param', help='parameters', nargs=2, action='append')
-        subcmd.add_argument('-u', '--auth', help='authorization key', default=props.get('AUTH'))
 
         self.addDefaultCommands(parser, props)
 
diff --git a/tools/cli/wskutil.py b/tools/cli/wskutil.py
index 7e8d786..75b7a38 100644
--- a/tools/cli/wskutil.py
+++ b/tools/cli/wskutil.py
@@ -45,7 +45,15 @@
 def bold(string):
     return hilite(string, True)
 
-def request(method, urlString, body = "", headers = {}, auth = None, verbose = False):
+def addAuthenticatedCommand(subcmd, props):
+    auth = props.get('AUTH')
+    #if auth is not None:
+    subcmd.add_argument('-u', '--auth', help='authorization key', default=auth)
+    #else:
+        # If a default authorization key is missing, make this a required positional argument
+        #subcmd.add_argument('auth', help='authorization key', default=auth)
+
+def request(method, urlString, body = '', headers = {}, auth = None, verbose = False):
     url = urlparse(urlString)
     if url.scheme == 'http':
         conn = httplib.HTTPConnection(url.netloc)
@@ -60,19 +68,19 @@
         headers['Authorization'] = 'Basic %s' % auth
     
     if verbose:
-        print "========"
-        print "REQUEST:"
-        print "%s %s" % (method, urlString)
-        print "Headers sent:"
+        print '========'
+        print 'REQUEST:'
+        print '%s %s' % (method, urlString)
+        print 'Headers sent:'
         print getPrettyJson(headers)
-        if body != "":
-            print "Body sent:"
+        if body != '':
+            print 'Body sent:'
             print body
 
     try:
         conn.request(method, urlString, body, headers)
         res = conn.getresponse()
-        body = ""
+        body = ''
         try:
             body = res.read()
         except httplib.IncompleteRead as e:
@@ -83,12 +91,12 @@
         res.read = lambda: body
 
         if verbose:
-            print "--------"
-            print "RESPONSE:"
-            print "Got response with code %s" % res.status
-            print "Body received:"
+            print '--------'
+            print 'RESPONSE:'
+            print 'Got response with code %s' % res.status
+            print 'Body received:'
             print res.read()
-            print "========"
+            print '========'
 
         return res
     except Exception, e:
@@ -184,7 +192,7 @@
     choosen = None
     while True:
         try:
-            keypress = raw_input("Choice: ")
+            keypress = raw_input('Choice: ')
             if keypress == 'x':
                 return -1
             choosen = int(keypress)
@@ -193,7 +201,7 @@
         if choosen > 0 and choosen < count:
             break
         else:
-            print "Please choose one of the given options"
+            print 'Please choose one of the given options'
     return array[choosen-1]
 
 # class to convert dictionary to objects
@@ -202,7 +210,7 @@
         if name in self:
             return self[name]
         else:
-            raise AttributeError("object has no attribute '%s'" % name)
+            raise AttributeError('object has no attribute "%s"' % name)
 
     def __setattr__(self, name, value):
         self[name] = value
@@ -211,7 +219,7 @@
         if name in self:
             del self[name]
         else:
-            raise AttributeError("object has no attribute '%s'" % name)
+            raise AttributeError('object has no attribute "%s"' % name)
 
 def getPrettyJson(obj):
     return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))