Skip to main content
  1. Posts/

Flask decorator for Netbox webhook authentication

·151 words·1 min·
netdevops blog python netbox webhook flask apiflask
Maximilian Thoma
Author
Maximilian Thoma
network engineer

Today, I am excited to share with you a decorator for Flask/APIFlask, specifically designed for Netbox webhook authentication. Although I have released this in the past, this time it is available as a decorator.

import hmac
from functools import wraps
from flask import request, current_app, abort


def check_netbox_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        x_hook_signature = request.headers.get('X-Hook-Signature', None)
        content_length = int(request.headers.get('Content-Length', 0))

        if content_length > 1_000_000:
            # To prevent memory allocation attacks
            abort(400, "Content too long")

        if x_hook_signature:
            # Check signature
            raw_input = request.data
            input_hmac = hmac.new(key=current_app.config['NETBOX_SECRET'].encode(), msg=raw_input, digestmod="sha512")
            if not hmac.compare_digest(input_hmac.hexdigest(), x_hook_signature):
                abort(400, "Invalid message signature")
        else:
            abort(400, "No message signature to check")
        return f(*args, **kwargs)

    return decorated

You can use this in your flask app like this:

from flask import Flask, request
from netbox_wrapper import check_netbox_auth

app = Flask(__name__)

# define your shared secret
app.config['NETBOX_SECRET'] = "secret"

@app.route("/netbox_webhook", methods=['POST'])
@check_netbox_auth
def netbox_hook():
    print(request.json)
    return {"status":"ok"}


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=6666)

Related

Netdevops python libraries toolbox
·1720 words·9 mins
netdevops blog python apiflask flask loguru ciscoconfparse dynaconf pymongo rq netmiko paramiko ansible pandas ntc_templates textfsm requests
In the ever-evolving landscape of network management and automation, the role of Network DevOps has become increasingly pivotal.
APIFlask Webhook Listener for Netbox
·258 words·2 mins
netdevops blog netbox python api apiflask
This little code snippet is the base of my Netbox Webhook Listener written in APIFlask.
FLASK with LDAP Authentication against Active Directory and group authorization for specific pages
·457 words·3 mins
netdevops blog python flask ldap active_directory
This is an example of how to implement authentication for a FLASK website using Active Directory with LDAP.