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:

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"}

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):
    def get(self):
        return jsonify({"access": "granted"})

api.add_resource(endpoint, "/secured_restful")

# --- classic api endpoint ---
def secured():
    return jsonify({"access": "granted"})

if __name__ == "__main__":, debug=True)

Start as:


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"