Secure Cloud Functions With Http Basic Authentication (HTTPBasicAuth) - Python

July 22, 2019

requirements.txt

# https://pypi.org/project/Flask-HTTPAuth/
Flask-HTTPAuth==3.3.0

main.py

from flask_httpauth import HTTPBasicAuth

auth = HTTPBasicAuth()

users = {
    "username": "password"
}

@auth.get_password
def get_password(username):
    return users.get(username)

@auth.login_required
def test_basic_auth(request):
    return f"{auth.username()}, you may pass!"

or using a more versatile verification method

from werkzeug.security import generate_password_hash, check_password_hash

users = {
    "username": generate_password_hash("password"),
    "another": generate_password_hash("secret")
}

@auth.verify_password
def verify_password(username, password):
    if username in users:
        return check_password_hash(users.get(username), password)
    return False

Test

curl -u username:password [URL]/test_basic_auth

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.