Flask-RESTful – Basic Authentication

I’m continuing to develop the REST API that will be used with the API.AI Webhook.  I decided that some sort of authentication is needed.

I played around with adding Basic Authentication to my API as API.AI supports this.  Below are the steps I took to get my authentication setup using Flask.  (Recommend reading Flask-HTTPAuth documentation)

  1. Include the necessary package
    • Flask-HTTPAuth==2.3.0
    • flaskauth
  2. Add get_password callback function.
    1. @auth.get_password
      def get_password(username):
          if username == 'devopsunleasheduser':
              return 'devopsunleashedpassword'
          return None
  3. Add error_handler callback function (Note “jsonify()” will need jsonify package)
    1. @auth.error_handler
      def unauthorized():
          # return 403 instead of 401 to prevent browsers from displaying the default
          # auth dialog
          return make_response(jsonify({'message': 'Unauthorized access'}), 403)
  4. Add login_required decorator to both classes to verify authentication before returning any info.
    1. decorators = [auth.login_required]