Flask API with Bear Token authentication

Here is an simple example of Flask API using bear token to authenticate the access. Authentication is achieved by using the annotation in python. Annotation under the cover is calling the “authenticate” method.

from flask import Flask, request, jsonify
from flask_restful import Api 

import subprocess

app = Flask(__name__)
api = Api(app)

TOKEN = 'hiworld'

def authenticate(func):
    def wrapper(*args, **kwargs):
        token = request.headers.get("Authorization")
        if token and token == f"Bearer {TOKEN}":
            return func(*args, **kwargs)
        else:
            return {"error": "Unauthorized"}, 401

    return wrapper

# Endpoint that runs a Python command
@app.route('/run_command', methods=['POST'])
@authenticate
def run_command():
    data = request.get_json()

    # Check if 'command' key exists in the JSON payload
    if 'command' not in data:
        return jsonify({'error': 'Command not provided'}), 400

    command = data['command']

    try:
        result = subprocess.check_output(command, shell=True, text=True)
        return jsonify({'result': result})
    except subprocess.CalledProcessError as e:
        return jsonify({'error': f'Error executing command: {e.output}'}), 500

if __name__ == '__main__':
    app.run(debug=True, port=8080)

To test the API, can use this curl command

curl -u your_username:your_password -X POST -H "Content-Type: application/json" -H "Authorization: Bearer hiworld" -d '{"command": "ls -lh"}' http://127.0.0.1:8081/run_command