Authentication Hook

Let’s create a simple example where we use a before hook to check for an authentication token in the request headers.

Step 1: Setting Up Falcon

Firstly, install Falcon if you haven’t installed already:

pip install falcon

Step 2: Writing the Hook

Create a file named app.py and start by importing the necessary modules and writing the hook function:

Python
#app.py
import falcon

# Define the authentication hook
def auth_hook(req, resp, resource, params):
    token = req.get_header('Authorization')
    if token != 'secret-token':
        raise falcon.HTTPUnauthorized('Authentication required',
                                      'Please provide a valid token.')
  • auth_hook is a function that checks for an Authorization header in the request.
  • If the token is not secret-token, it raises an HTTPUnauthorized exception, which results in a 401 Unauthorized response.

Step 3: Creating a Resource

Next, define a resource where the hook will be applied:

Python
#app.py

# Define the resource with request handlers
class ResourceWithAuth:
    @falcon.before(auth_hook)
    def on_get(self, req, resp):
        resp.media = {'message': 'You are authenticated!'}

    @falcon.before(auth_hook)
    def on_post(self, req, resp):
        resp.media = {'message': 'Data received!'}

ResourceWithAuth is a resource class with two methods:

  • on_get: Handles GET requests and responds with a JSON message.
  • on_post: Handles POST requests and responds with a JSON message.


Step 4: Setting Up the API

Set up the Falcon API and add the route:

Python
#app.py continue...

# Set up the Falcon API and add the route
app = falcon.App()
app.add_route('/secure', ResourceWithAuth())

# Run the application using the built-in WSGI server
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    with make_server('', 8000, app) as httpd:
        print('Serving on port 8000...')
        httpd.serve_forever()

Running the Application

Run your Falcon application, using:

python app.py

You should see the output indicating that the server is running:

output

Python Falcon – Hooks

In Falcon, hooks are type of callbacks that are defined by the user and are executed before or after a responder method in a particular resource class to process client request. They are useful in as much as they allow a client to add or overwrite request processing functionality at certain predefined stages.

Similar Reads

Understanding Hooks in Python Falcon

Falcon offers two types of hooks:...

Using Hooks

Falcon provides two decorators, @falcon.before and @falcon.after, for hanging callbacks on responder methods, or indeed on whole classes of resources. The arguments passed to hook functions include:...

Example: Authentication Hook

Let’s create a simple example where we use a before hook to check for an authentication token in the request headers....

Testing the Hook

Let’s test our before hook using curl:...

Example: Logging (After Hooks)

After hooks are defined similarly but are used to modify the response:...

Advanced Hook Usage

Multiple Hooks...

Common Use Cases for Falcon Hooks

Authentication and Authorization:...