flaskflask-httpauth

Understand decorators on Flask-HTTPAuth


I want to understand how and when @auth.verify_password decorator is used on this program. If i navigate to route http://127.0.0.1:5000, I understand that I need to passed in a username and a password and @auth.login_required will verify it, but where does @auth.verify_password comes in?

Does @auth.login_required calls it?

#!/usr/bin/env python
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": generate_password_hash("hello"),
    "susan": generate_password_hash("bye")
}


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


@app.route('/')
@auth.login_required
def index():
    return "Hello, %s!" % auth.username()


if __name__ == '__main__':
    app.run()

Solution

  • From the documentation:

    verify_password(verify_password_callback)

    If defined, this callback function will be called by the framework to verify that the username and password combination provided by the client are valid. The callback function takes two arguments, the username and the password and must return True or False.

    So you basically provide the function so your program is able to verify the credentials supplied by the user.

    The login_required decorator protects the route by reading the authentication credentials provided by the user and passing them to your verify_password function to be verified.