FLASK-HTTPAUTH(3)
π FLASK-HTTPAUTH(3) β Flask-HTTPAuth π
okay so bestie, welcome to the FLASK-HTTPAUTH(3) manual page π this whole thing is the Flask-HTTPAuth documentation, and it's literally the glow-up your Flask routes have been waiting for. grab a boba, we're doing auth today. π§β¨
β¨ NAME β¨
flask-httpauth β Flask-HTTPAuth Documentation π
Flask-HTTPAuth is a Flask extension that simplifies the use of HTTP authentication with Flask routes. like, it takes the whole "how do I even do auth" situation and makes it cute. no cap. π¦
π GETTING STARTED π
π¦ Installation
You can install Flask-HTTPAuth with pip:
pip install flask-httpauth
and that's it, that's the whole install, slay π«Ά
π Basic authentication example
okay so here's a whole lil application that uses HTTP Basic authentication to protect route '/':
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 and \
check_password_hash(users.get(username), password):
return username
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.current_user())
if __name__ == '__main__':
app.run()
so the function decorated with the verify_password decorator receives the username and password sent by the client. if the credentials belong to a user, then the function should return the user object. if the credentials are invalid the function can return None or False. and then β this is the cute part β the user object can be queried from the current_user() method of the authentication instance. obsessed. πΈ
π Digest authentication example
next up, HTTP Digest authentication:
from flask import Flask
from flask_httpauth import HTTPDigestAuth
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
auth = HTTPDigestAuth()
users = {
"john": "hello",
"susan": "bye"
}
@auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.username())
if __name__ == '__main__':
app.run()
heads up bestie, that app.config['SECRET_KEY'] = 'secret key here' is doing heavy lifting, don't skip it π
ποΈ Token Authentication Example
and now, a custom HTTP authentication scheme protecting route '/' with a token:
from flask import Flask
from flask_httpauth import HTTPTokenAuth
app = Flask(__name__)
auth = HTTPTokenAuth(scheme='Bearer')
tokens = {
"secret-token-1": "john",
"secret-token-2": "susan"
}
@auth.verify_token
def verify_token(token):
if token in tokens:
return tokens[token]
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.current_user())
if __name__ == '__main__':
app.run()
so HTTPTokenAuth is a generic authentication handler that can be used with non-standard authentication schemes, with the scheme name given as an argument in the constructor. in the above example, the WWW-Authenticate header provided by the server will use Bearer as scheme:
WWW-Authenticate: Bearer realm="Authentication Required"
The verify_token callback receives the authentication credentials provided by the client on the Authorization header. This can be a simple token, or can contain multiple arguments, which the function will have to parse and extract from the string. As with the verify_password, the function should return the user object if the token is valid. π
In the examples directory you can find a complete example that uses JWS tokens. JWS tokens are similar to JWT tokens. However using JWT tokens would require an external dependency. (iykyk π)
π Using Multiple Authentication Schemes
Applications sometimes need to support a combination of authentication methods. For example, a web application could be authenticated by sending client id and secret over basic authentication, while third party API clients use a JWS or JWT bearer token. The MultiAuth class allows you to protect a route with more than one authentication object. To grant access to the endpoint, one of the authentication methods must validate.
In the examples directory you can find a complete example that uses basic and token authentication. β¨
π User Roles
Flask-HTTPAuth includes a simple role-based authentication system that can optionally be added to provide an additional layer of granularity in filtering accesses to routes. To enable role support, write a function that returns the list of roles for a given user and decorate it with the get_user_roles decorator:
@auth.get_user_roles
def get_user_roles(user):
return user.get_roles()
To restrict access to a route to users having a given role, add the role argument to the login_required decorator:
@app.route('/admin')
@auth.login_required(role='admin')
def admins_only():
return "Hello {}, you are an admin!".format(auth.current_user())
The role argument can take a list of roles, in which case users who have any of the given roles will be granted access:
@app.route('/admin')
@auth.login_required(role=['admin', 'moderator'])
def admins_only():
return "Hello {}, you are an admin or a moderator!".format(auth.current_user())
And in the most advanced usage, users can be filtered by having multiple roles:
@app.route('/admin')
@auth.login_required(role=['user', ['moderator', 'contributor']])
def admins_only():
return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user())
the way that nested list just works? main character energy, periodt. π
π οΈ Deployment Considerations
Be aware that some web servers do not pass the Authorization headers to the WSGI application by default. For example, if you use Apache with mod_wsgi, you have to set option WSGIPassAuthorization On as documented here https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization/.
bestie do NOT forget this one, your auth will just silently not work and you'll be debugging for three hours crying π
π°οΈ Deprecated Basic Authentication Options
okay so before the verify_password described above existed there were other simpler mechanisms for implementing basic authentication. While these are deprecated they are still maintained. However, the verify_password callback should be preferred as it provides greater security and flexibility. (translation: use the new one, the old one is giving 2014 π« )
The get_password callback needs to return the password associated with the username given as argument. Flask-HTTPAuth will allow access only if get_password(username) == password. Example:
@auth.get_password
def get_password(username):
return get_password_for_username(username)
Using this callback alone is in general not a good idea because it requires passwords to be available in plaintext in the server. π¨ (yes, plaintext. screaming.) In the more likely scenario that the passwords are stored hashed in a user database, then an additional callback is needed to define how to hash a password:
@auth.hash_password
def hash_pw(password):
return hash_password(password)
In this example, you have to replace hash_password() with the specific hashing function used in your application. When the hash_password callback is provided, access will be granted when get_password(username) == hash_password(password).
If the hashing algorithm requires the username to be known then the callback can take two arguments instead of one:
@auth.hash_password
def hash_pw(username, password):
salt = get_salt(username)
return hash_password(password, salt)
π API DOCUMENTATION π
class flask_httpauth.HTTPBasicAuth(scheme=None, realm=None)
Create a basic authentication object. π
If the optional scheme argument is provided, it will be used instead of the standard "Basic" scheme in the WWW-Authenticate response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login.
The realm argument can be used to provide an application defined realm with the WWW-Authenticate header.
current_user()
The user object returned by the verify_password callback on successful authentication. If no user is returned by the callback, this is set to the username passed by the client. Example:
@app.route('/')
@auth.login_required
def index():
user = auth.current_user()
return "Hello, {}!".format(user.name)
error_handler(f)
Decorator for a function that will be called by the framework when it is necessary to send an authentication error back to the client. The function can take one argument, the status code of the error, which can be 401 (incorrect credentials) or 403 (correct, but insufficient credentials). To preserve compatiiblity with older releases of this package, the function can also be defined without arguments. The return value from this function must by any accepted response type in Flask routes. If this callback isn't provided a default error response is generated. Example:
@auth.error_handler
def auth_error(status):
return "Access Denied", status
get_password(f)
Deprecated Decorator for a function that will be called by the framework to obtain the password for a given user. Example:
@auth.get_password
def get_password(username):
return db.get_user_password(username)
deprecated bestie!! it still works but it's giving legacy, we've moved on π
get_user_roles(f)
Decorator for a function that will be called by the framework to obtain the roles assigned to a given user. The callback function takes a single argument, the user for which roles are requested. The user object passed to this function will be the one returned by the "verify" callback. If the verify callback returned True instead of a user object, then the Authorization object provided by Flask will be passed to this function. The function should return the role or list of roles that belong to the user. Example:
@auth.get_user_roles
def get_user_roles(user):
return user.get_roles()
okay so that's the first chunk, and there's more coming, don't go anywhere bestie π¦π
π
hash_password(f)
Deprecated, bestie β still here, still works, but she's retired. This is a decorator for a function the framework will call so you can apply your own custom hashing algorithm to the password the client handed over. If you don't provide this callback, the password just gets checked unchanged. No glow-up at all. π
The callback can take one or two arguments:
- the one-argument version gets the password to hash
- the two-argument version gets the username and the password, in that order
Example of the single-argument callback:
@auth.hash_password
def hash_password(password):
return md5(password).hexdigest()
Example of the two-argument callback:
@auth.hash_password
def hash_pw(username, password):
salt = get_salt(username)
return hash(password, salt)
π login_required(f=None, role=None, optional=None)
This is the moment β the decorator for a function that gets called when authentication succeeds. Usually that function is a Flask view. Example:
@app.route('/private')
@auth.login_required
def private_page():
return "Only for authorized people!"
You can also pass an optional role argument to restrict access even further by roles. Because gatekeeping is a love language. β¨
@app.route('/private')
@auth.login_required(role='admin')
def private_page():
return "Only for admins!"
There's also an optional optional argument β set it to True and the route is allowed to run even when the request doesn't include authentication at all. In that case auth.current_user() gets set to None. Example:
@app.route('/private')
@auth.login_required(optional=True)
def private_page():
user = auth.current_user()
return "Hello {}!".format(
user.name if user is not None else 'anonymous')
πΈ username()
Deprecated! If a view function is protected with this class, it can grab the logged username through this method. Example:
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.username())
β
verify_password(f)
Decorator for a function the framework calls to check that the username + password combo the client sent is actually valid. The callback takes two arguments β the username and the password β and it has to return:
- the user object if the credentials are valid, or
Trueif a user object isn't available
And when authentication fails, it should return None or False. No half measures, bestie. π
Example usage:
@auth.verify_password
def verify_password(username, password):
user = User.query.filter_by(username).first()
if user and passlib.hash.sha256_crypt.verify(
password, user.password_hash):
return user
Here's the spicy part: if this callback is defined, it also gets invoked when the request has no Authorization header with user credentials at all β and in that case both the username and password arguments are set to empty strings. The application can choose to return True in that situation, which lets anonymous users access the route. The callback can signal that the user is anonymous either by writing a state variable to flask.g, or by checking whether auth.current_user() is None.
β οΈ Note this, it's important: when averify_passwordcallback is provided, theget_passwordandhash_passwordcallbacks are not used. Periodt.
π class flask_httpauth.HTTPDigestAuth(scheme=None, realm=None, use_ha1_pw=False, qop='auth', algorithm='MD5')
Create a digest authentication object. Iconic. π
- If the optional
schemeargument is provided, it's used instead of the"Digest"scheme in theWWW-Authenticateresponse. A fairly common flex is using a custom scheme so browsers don't pop up that login prompt at your users. - The
realmargument lets you provide an application-defined realm with theWWW-Authenticateheader. - If
use_ha1_pwisFalse, then theget_passwordcallback needs to return the plain text password for the given user. Ifuse_ha1_pwisTrue, then theget_passwordcallback needs to return the HA1 value for the given user. The advantage of settinguse_ha1_pwtoTrueis that it lets the application store the HA1 hash of the password in the user database. Storing hashes > storing vibes. - The
qopoption configures a list of accepted quality of protection extensions. You can give this argument as a comma-separated string, a list of strings, orNoneto disable it. The default isauth. Heads up: theauth-intoption is currently not implemented. π - The
algorithmoption configures the hash generation algorithm to use. The default isMD5. The two algorithms that are implemented areMD5andMD5-Sess.
π«Ά current_user()
The user object returned by the verify_password callback on successful authentication. If the callback didn't return a user, this gets set to the username the client passed. Example:
@app.route('/')
@auth.login_required
def index():
user = auth.current_user()
return "Hello, {}!".format(user.name)
π error_handler(f)
Decorator for a function the framework calls whenever it needs to send an authentication error back to the client. The function can take one argument β the status code of the error β which can be:
401β incorrect credentials403β correct credentials, but insufficient ones
To preserve compatibility with older releases of this package, the function can also be defined with no arguments at all. The return value from this function has to be any accepted response type in Flask routes. If you don't provide this callback, a default error response gets generated for you. Example:
@auth.error_handler
def auth_error(status):
return "Access Denied", status
π§ generate_ha1(username, password)
Generate the HA1 hash that you can store in the user database when use_ha1_pw is set to True in the constructor. Pre-computing? We love efficiency. β¨
π¦ generate_nonce(f)
If you define this callback function, the framework will call it to generate a nonce. And if this is defined, verify_nonce should also be defined β they're a package deal, iykyk.
This can be used if you want a state storage mechanism other than the session.
π generate_opaque(f)
Decorator for a function the framework calls to generate an opaque value. If this is defined, verify_opaque should also be defined. Same buddy system as above. π«Ά
This can be used if you want a state storage mechanism other than the session.
π get_password(f)
Deprecated! Decorator for a function the framework calls to obtain the password for a given user. Example:
@auth.get_password
def get_password(username):
return db.get_user_password(username)
π get_user_roles(f)
Decorator for a function the framework calls to obtain the roles assigned to a given user. The callback takes a single argument β the user that roles are being requested for. That user object is the one returned by the "verify" callback. And if the verify callback returned True instead of a user object, then the Authorization object provided by Flask gets passed to this function instead. The function should return the role, or a list of roles, that belong to the user. Example:
@auth.get_user_roles
def get_user_roles(user):
return user.get_roles()
π login_required(f=None, role=None, optional=None)
Decorator for a function that gets called when authentication succeeds. Typically a Flask view function. Example:
@app.route('/private')
@auth.login_required
def private_page():
return "Only for authorized people!"
An optional role argument can be given to further restrict access by roles. Example:
@app.route('/private')
@auth.login_required(role='admin')
def private_page():
return "Only for admins!"
An optional optional argument can be set to True to allow the route to execute even when authentication isn't included with the request β in which case auth.current_user() will be set to None. Example:
@app.route('/private')
@auth.login_required(optional=True)
def private_page():
user = auth.current_user()
return "Hello {}!".format(
user.name if user is not None else 'anonymous')
πΈ username()
Deprecated! A view function protected with this class can access the logged username through this method. Example:
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.username())
okay bestie we're still in the API docs, no re-intro needed, we're just gonna KEEP GOING π β¨
verify_nonce(f)β a decorator for a function that the framework will call to verify that a nonce is valid. It gets called with a single argument: the nonce to be verified. This is the move when you wanna use a state storage mechanism that is not the session. πverify_opaque(f)β same energy, different value. A decorator for a function the framework calls to verify that an opaque value is valid. Again, one single argument: the opaque value to be verified. And again β this is how you use a state storage mechanism other than the session. π¦
class flask_httpauth.HTTPTokenAuth(scheme='Bearer', realm=None, header=None)
current_user()β the user object that came back from theverify_passwordcallback after a successful authentication. And bestie, listen: if the callback doesn't return a user, then this gets set to the username the client passed in. No user object, no problem, you still get the name. π
@app.route('/')
@auth.login_required
def index():
user = auth.current_user()
return "Hello, {}!".format(user.name)
error_handler(f)β decorator for a function the framework calls when it has to send an authentication error back to the client. That function can take one argument, the status code of the error, which can be401(incorrect credentials) or403(correct, but insufficient credentials). For compatibility with older releases of this package, the function can also be defined with no arguments at all. Whatever it returns has to be any accepted response type in Flask routes. If you don't provide this callback, a default error response just gets generated for you. β¨
@auth.error_handler
def auth_error(status):
return "Access Denied", status
get_password(f)β Deprecated π« Decorator for a function the framework calls to obtain the password for a given user.
@auth.get_password
def get_password(username):
return db.get_user_password(username)
get_user_roles(f)β decorator for a function the framework calls to obtain the roles assigned to a given user. The callback takes a single argument: the user the roles are being requested for. The user object handed to this function is the one returned by the"verify"callback. But if that verify callback returnedTrueinstead of a user object, then theAuthorizationobject provided by Flask is what gets passed in here. The function should return the role, or a list of roles, that belong to the user. π
@auth.get_user_roles
def get_user_roles(user):
return user.get_roles()
login_required(f=None, role=None, optional=None)β decorator for a function that gets called when authentication succeeds. Usually that's a Flask view function, iykyk. πΈ
@app.route('/private')
@auth.login_required
def private_page():
return "Only for authorized people!"
You can also hand it an optional role argument to further restrict access by roles:
@app.route('/private')
@auth.login_required(role='admin')
def private_page():
return "Only for admins!"
And there's an optional optional argument β set it to True and the route will execute even when authentication is not included with the request, in which case auth.current_user() gets set to None. π
@app.route('/private')
@auth.login_required(optional=True)
def private_page():
user = auth.current_user()
return "Hello {}!".format(
user.name if user is not None else 'anonymous')
username()β Deprecated π« A view function protected with this class can still reach the logged-in username through this method.
@app.route('/')
@auth.login_required
def index():
return "Hello, {}!".format(auth.username())
verify_token(f)β decorator for a function the framework calls to verify that the credentials the client sent with theAuthorizationheader are actually valid. The callback takes one argument: the token the client provided. It must return the user object if the token is valid, orTrueif a user object isn't available. If authentication failed, the function should returnNoneorFalse. π
@auth.verify_token
def verify_token(token):
return User.query.filter_by(token=token).first()
β οΈ Note that a verify_token callback is required when using this class. Not optional, not a vibe, required. periodt.
class flask_httpauth.MultiAuth(main_auth, *additional_auths)
Create a multiple authentication object. π
The arguments are one or more instances of HTTPBasicAuth, HTTPDigestAuth or HTTPTokenAuth. A route protected with this authentication method will try all the given authentication objects until one of them succeeds. It's giving "we have options and we will use all of them". π
current_user()β the authenticated user.login_required(f=None, role=None, optional=None)β decorator for a function that will be called when authentication is successful. Typically a Flask view function.
- Index <>
- Module Index <>
- Search Page <>
Author
Miguel Grinberg π
Copyright
2013, Miguel Grinberg
and that's a wrap on the whole page, bestie!! π this bad boy is FLASK-HTTPAUTH(3), dated Apr 21, 2026, and honestly? iconic documentation, no notes, we ate and left absolutely no crumbs πβ¨π¦πΈπ«Ά
π¦ where this page comes from
- ubuntu stonking: python3-flask-httpauth 4.8.1-1.1 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms