How to protect Flask API endpoint with password (HTTPBasicAuth)

Let's say we have flask API running on the server, but want only authenticated users to use it. We have several options: cookie based authentication, JWT tokens and of course simple authentication with username and password.

In this article we will create quick demo uf username/password approach with library called flask_httpauth.

First install dependencies:

pip3 install flask flask_restful flask_httpauth

The actual flask app:

# code source:
# https://www.youtube.com/watch?v=Z6u-dEnzkUs
# https://flask-httpauth.readthedocs.io/en/latest/

from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_httpauth import HTTPBasicAuth

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

USER_DATA = {"username": "password"}

@auth.verify_password
def verify(username, password):
    if not (username and password):
        return False

    # return statement checks 
    # if value for key username (user provided password)
    # equals expected password we have stored locally
    # True/False
    return USER_DATA.get(username) == password

# --- flask_restful endpoint ---
class endpoint(Resource):
    @auth.login_required
    def get(self):
        return jsonify({"access": "granted"})

api.add_resource(endpoint, "/secured_restful")

# --- classic api endpoint ---
@app.route("/secured_api")
@auth.login_required
def secured():
    return jsonify({"access": "granted"})

if __name__ == "__main__":
    app.run(port=5000, debug=True)

Start as:

python3 app.py

Perform test authentication with curl to both endpoints:

coil@coil-VM:~/Desktop$ curl -u username:password http://localhost:5000/secured_restful
{
  "access": "granted"
}
coil@coil-VM:~/Desktop$ curl -u username:password http://localhost:5000/secured_api
{
  "access": "granted"
}
coil@coil-VM:~/Desktop$ 

Sources: