.\" Man page generated from reStructuredText. . . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .TH "FLASK-HTTPAUTH" "3" "Jan 25, 2022" "" "Flask-HTTPAuth" .SH NAME flask-httpauth \- Flask-HTTPAuth Documentation .sp \fBFlask\-HTTPAuth\fP is a Flask extension that simplifies the use of HTTP authentication with Flask routes. .SH BASIC AUTHENTICATION EXAMPLES .sp The following example application uses HTTP Basic authentication to protect route \fB\(aq/\(aq\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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 \e check_password_hash(users.get(username), password): return username @app.route(\(aq/\(aq) @auth.login_required def index(): return "Hello, {}!".format(auth.current_user()) if __name__ == \(aq__main__\(aq: app.run() .ft P .fi .UNINDENT .UNINDENT .sp The function decorated with the \fBverify_password\fP 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 \fBNone\fP or \fBFalse\fP\&. The user object can then be queried from the \fBcurrent_user()\fP method of the authentication instance. .SH DIGEST AUTHENTICATION EXAMPLE .sp The following example uses HTTP Digest authentication: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.config[\(aqSECRET_KEY\(aq] = \(aqsecret key here\(aq 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(\(aq/\(aq) @auth.login_required def index(): return "Hello, {}!".format(auth.username()) if __name__ == \(aq__main__\(aq: app.run() .ft P .fi .UNINDENT .UNINDENT .SS Security Concerns with Digest Authentication .sp The digest authentication algorithm requires a \fIchallenge\fP to be sent to the client for use in encrypting the password for transmission. This challenge needs to be used again when the password is decoded at the server, so the challenge information needs to be stored so that it can be recalled later. .sp By default, Flask\-HTTPAuth stores the challenge data in the Flask session. To make the authentication flow secure when using session storage, it is required that server\-side sessions are used instead of the default Flask cookie based sessions, as this ensures that the challenge data is not at risk of being captured as it moves in a cookie between server and client. The Flask\-Session and Flask\-KVSession extensions are both very good options to implement server\-side sessions. .sp As an alternative to using server\-side sessions, an application can implement its own generation and storage of challenge data. To do this, there are four callback functions that the application needs to implement: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @auth.generate_nonce def generate_nonce(): """Return the nonce value to use for this client.""" pass @auth.generate_opaque def generate_opaque(): """Return the opaque value to use for this client.""" pass @auth.verify_nonce def verify_nonce(nonce): """Verify that the nonce value sent by the client is correct.""" pass @auth.verify_opaque def verify_opaque(opaque): """Verify that the opaque value sent by the client is correct.""" pass .ft P .fi .UNINDENT .UNINDENT .sp For information of what the \fBnonce\fP and \fBopaque\fP values are and how they are used in digest authentication, consult \fI\%RFC 2617\fP\&. .SH TOKEN AUTHENTICATION EXAMPLE .sp The following example application uses a custom HTTP authentication scheme to protect route \fB\(aq/\(aq\fP with a token: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import Flask from flask_httpauth import HTTPTokenAuth app = Flask(__name__) auth = HTTPTokenAuth(scheme=\(aqBearer\(aq) 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(\(aq/\(aq) @auth.login_required def index(): return "Hello, {}!".format(auth.current_user()) if __name__ == \(aq__main__\(aq: app.run() .ft P .fi .UNINDENT .UNINDENT .sp The \fBHTTPTokenAuth\fP 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 \fBWWW\-Authenticate\fP header provided by the server will use \fBBearer\fP as scheme: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C WWW\-Authenticate: Bearer realm="Authentication Required" .ft P .fi .UNINDENT .UNINDENT .sp The \fBverify_token\fP callback receives the authentication credentials provided by the client on the \fBAuthorization\fP 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 \fBverify_password\fP, the function should return the user object if the token is valid. .sp 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. .SH USING MULTIPLE AUTHENTICATION SCHEMES .sp 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 \fIMultiAuth\fP 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. .sp In the examples directory you can find a complete example that uses basic and token authentication. .SH USER ROLES .sp 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 \fBget_user_roles\fP decorator: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @auth.get_user_roles def get_user_roles(user): return user.get_roles() .ft P .fi .UNINDENT .UNINDENT .sp To restrict access to a route to users having a given role, add the \fBrole\fP argument to the \fBlogin_required\fP decorator: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/admin\(aq) @auth.login_required(role=\(aqadmin\(aq) def admins_only(): return "Hello {}, you are an admin!".format(auth.current_user()) .ft P .fi .UNINDENT .UNINDENT .sp The \fBrole\fP argument can take a list of roles, in which case users who have any of the given roles will be granted access: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/admin\(aq) @auth.login_required(role=[\(aqadmin\(aq, \(aqmoderator\(aq]) def admins_only(): return "Hello {}, you are an admin or a moderator!".format(auth.current_user()) .ft P .fi .UNINDENT .UNINDENT .sp In the most advanced usage, users can be filtered by having multiple roles: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/admin\(aq) @auth.login_required(role=[\(aquser\(aq, [\(aqmoderator\(aq, \(aqcontributor\(aq]]) def admins_only(): return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user()) .ft P .fi .UNINDENT .UNINDENT .SH DEPLOYMENT CONSIDERATIONS .sp Be aware that some web servers do not pass the \fBAuthorization\fP headers to the WSGI application by default. For example, if you use Apache with mod_wsgi, you have to set option \fBWSGIPassAuthorization On\fP as \fI\%documented here\fP\&. .SH DEPRECATED BASIC AUTHENTICATION OPTIONS .sp Before the \fBverify_password\fP described above existed there were other simpler mechanisms for implementing basic authentication. While these are deprecated they are still maintained. However, the \fBverify_password\fP callback should be preferred as it provides greater security and flexibility. .sp The \fBget_password\fP callback needs to return the password associated with the username given as argument. Flask\-HTTPAuth will allow access only if \fBget_password(username) == password\fP\&. Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @auth.get_password def get_password(username): return get_password_for_username(username) .ft P .fi .UNINDENT .UNINDENT .sp Using this callback alone is in general not a good idea because it requires passwords to be available in plaintext in the server. 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @auth.hash_password def hash_pw(password): return hash_password(password) .ft P .fi .UNINDENT .UNINDENT .sp In this example, you have to replace \fBhash_password()\fP with the specific hashing function used in your application. When the \fBhash_password\fP callback is provided, access will be granted when \fBget_password(username) == hash_password(password)\fP\&. .sp If the hashing algorithm requires the username to be known then the callback can take two arguments instead of one: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @auth.hash_password def hash_pw(username, password): salt = get_salt(username) return hash_password(password, salt) .ft P .fi .UNINDENT .UNINDENT .SH API DOCUMENTATION .INDENT 0.0 .TP .B class flask_httpauth.HTTPBasicAuth This class handles HTTP Basic authentication for Flask routes. .INDENT 7.0 .TP .B __init__(scheme=None, realm=None) Create a basic authentication object. .sp If the optional \fBscheme\fP argument is provided, it will be used instead of the standard "Basic" scheme in the \fBWWW\-Authenticate\fP response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. .sp The \fBrealm\fP argument can be used to provide an application defined realm with the \fBWWW\-Authenticate\fP header. .UNINDENT .INDENT 7.0 .TP .B 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. It must return the user object if credentials are valid, or \fBTrue\fP if a user object is not available. In case of failed authentication, it should return \fBNone\fP or \fBFalse\fP\&. Example usage: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @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 .ft P .fi .UNINDENT .UNINDENT .sp If this callback is defined, it is also invoked when the request does not have the \fBAuthorization\fP header with user credentials, and in this case both the \fBusername\fP and \fBpassword\fP arguments are set to empty strings. The application can opt to return \fBTrue\fP in this case and that will allow anonymous users access to the route. The callback function can indicate that the user is anonymous by writing a state variable to \fBflask.g\fP or by checking if \fBauth.current_user()\fP is \fBNone\fP\&. .sp Note that when a \fBverify_password\fP callback is provided the \fBget_password\fP and \fBhash_password\fP callbacks are not used. .UNINDENT .INDENT 7.0 .TP .B get_user_roles(roles_callback) If defined, this callback function 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 \fBverify_callback\fP function. The function should return the role or list of roles that belong to the user. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.get_user_roles def get_user_roles(user): return user.get_roles() .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B get_password(password_callback) \fIDeprecated\fP This callback function will be called by the framework to obtain the password for a given user. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.get_password def get_password(username): return db.get_user_password(username) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B hash_password(hash_password_callback) \fIDeprecated\fP If defined, this callback function will be called by the framework to apply a custom hashing algorithm to the password provided by the client. If this callback isn\(aqt provided the password will be checked unchanged. The callback can take one or two arguments. The one argument version receives the password to hash, while the two argument version receives the username and the password in that order. Example single argument callback: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.hash_password def hash_password(password): return md5(password).hexdigest() .ft P .fi .UNINDENT .UNINDENT .sp Example two argument callback: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.hash_password def hash_pw(username, password): salt = get_salt(username) return hash(password, salt) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B error_handler(error_callback) If defined, this callback function 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\(aqt provided a default error response is generated. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.error_handler def auth_error(status): return "Access Denied", status .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B login_required(view_function_callback) This callback function will be called when authentication is successful. This will typically be a Flask view function. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/private\(aq) @auth.login_required def private_page(): return "Only for authorized people!" .ft P .fi .UNINDENT .UNINDENT .sp An optional \fBrole\fP argument can be given to further restrict access by roles. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/private\(aq) @auth.login_required(role=\(aqadmin\(aq) def private_page(): return "Only for admins!" .ft P .fi .UNINDENT .UNINDENT .sp An optional \fBoptional\fP argument can be set to \fBTrue\fP to allow the route to execute also when authentication is not included with the request, in which case \fBauth.current_user()\fP will be set to \fBNone\fP\&. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/private\(aq) @auth.login_required(optional=True) def private_page(): user = auth.current_user() return "Hello {}!".format(user.name if user is not None else \(aqanonymous\(aq) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B current_user() The user object returned by the \fBverify_password\fP callback on successful authentication. If no user is returned by the callback, this is set to the username passed by the client. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/\(aq) @auth.login_required def index(): user = auth.current_user() return "Hello, {}!".format(user.name) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B username() \fIDeprecated\fP A view function that is protected with this class can access the logged username through this method. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @app.route(\(aq/\(aq) @auth.login_required def index(): return "Hello, {}!".format(auth.username()) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B class flask_httpauth.HTTPDigestAuth This class handles HTTP Digest authentication for Flask routes. The \fBSECRET_KEY\fP configuration must be set in the Flask application to enable the session to work. Flask by default stores user sessions in the client as secure cookies, so the client must be able to handle cookies. To make this authentication method secure, a \fI\%session interface\fP that writes sessions in the server must be used. .INDENT 7.0 .TP .B __init__(self, scheme=None, realm=None, use_ha1_pw=False) Create a digest authentication object. .sp If the optional \fBscheme\fP argument is provided, it will be used instead of the "Digest" scheme in the \fBWWW\-Authenticate\fP response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. .sp The \fBrealm\fP argument can be used to provide an application defined realm with the \fBWWW\-Authenticate\fP header. .sp If \fBuse_ha1_pw\fP is False, then the \fBget_password\fP callback needs to return the plain text password for the given user. If \fBuse_ha1_pw\fP is True, the \fBget_password\fP callback needs to return the HA1 value for the given user. The advantage of setting \fBuse_ha1_pw\fP to \fBTrue\fP is that it allows the application to store the HA1 hash of the password in the user database. .UNINDENT .INDENT 7.0 .TP .B generate_ha1(username, password) Generate the HA1 hash that can be stored in the user database when \fBuse_ha1_pw\fP is set to True in the constructor. .UNINDENT .INDENT 7.0 .TP .B generate_nonce(nonce_making_callback) If defined, this callback function will be called by the framework to generate a nonce. If this is defined, \fBverify_nonce\fP should also be defined. .sp This can be used to use a state storage mechanism other than the session. .UNINDENT .INDENT 7.0 .TP .B verify_nonce(nonce_verify_callback) If defined, this callback function will be called by the framework to verify that a nonce is valid. It will be called with a single argument: the nonce to be verified. .sp This can be used to use a state storage mechanism other than the session. .UNINDENT .INDENT 7.0 .TP .B generate_opaque(opaque_making_callback) If defined, this callback function will be called by the framework to generate an opaque value. If this is defined, \fBverify_opaque\fP should also be defined. .sp This can be used to use a state storage mechanism other than the session. .UNINDENT .INDENT 7.0 .TP .B verify_opaque(opaque_verify_callback) If defined, this callback function will be called by the framework to verify that an opaque value is valid. It will be called with a single argument: the opaque value to be verified. .sp This can be used to use a state storage mechanism other than the session. .UNINDENT .INDENT 7.0 .TP .B get_password(password_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B get_user_roles(roles_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B error_handler(error_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B login_required(view_function_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B current_user() See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B username() See basic authentication for documentation and examples. .UNINDENT .UNINDENT .INDENT 0.0 .TP .B class flask_httpauth.HTTPTokenAuth This class handles HTTP authentication with custom schemes for Flask routes. .INDENT 7.0 .TP .B __init__(scheme=\(aqBearer\(aq, realm=None, header=None) Create a token authentication object. .sp The \fBscheme\fP argument can be use to specify the scheme to be used in the \fBWWW\-Authenticate\fP response. The \fBAuthorization\fP header sent by the client must include this scheme followed by the token. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C Authorization: Bearer this\-is\-my\-token .ft P .fi .UNINDENT .UNINDENT .sp The \fBrealm\fP argument can be used to provide an application defined realm with the \fBWWW\-Authenticate\fP header. .sp The \fBheader\fP argument can be used to specify a custom header instead of \fBAuthorization\fP from where to obtain the token. If a custom header is used, the \fBscheme\fP should not be included. Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C X\-API\-Key: this\-is\-my\-token .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B verify_token(verify_token_callback) This callback function will be called by the framework to verify that the credentials sent by the client with the \fBAuthorization\fP header are valid. The callback function takes one argument, the token provided by the client. The function must return the user object if the token is valid, or \fBTrue\fP if a user object is not available. In case of a failed authentication, the function should return \fBNone\fP or \fBFalse\fP\&. Example usage: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C @auth.verify_token def verify_token(token): return User.query.filter_by(token=token).first() .ft P .fi .UNINDENT .UNINDENT .sp Note that a \fBverify_token\fP callback is required when using this class. .UNINDENT .INDENT 7.0 .TP .B get_user_roles(roles_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B error_handler(error_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B login_required(view_function_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B current_user() See basic authentication for documentation and examples. .UNINDENT .UNINDENT .INDENT 0.0 .TP .B class flask_httpauth.HTTPMultiAuth This class handles HTTP authentication with custom schemes for Flask routes. .INDENT 7.0 .TP .B __init__(auth_object, \&...) Create a multiple authentication object. .sp The arguments are one or more instances of \fBHTTPBasicAuth\fP, \fBHTTPDigestAuth\fP or \fBHTTPTokenAuth\fP\&. A route protected with this authentication method will try all the given authentication objects until one succeeds. .UNINDENT .INDENT 7.0 .TP .B login_required(view_function_callback) See basic authentication for documentation and examples. .UNINDENT .INDENT 7.0 .TP .B current_user() See basic authentication for documentation and examples. .UNINDENT .UNINDENT .SH AUTHOR Miguel Grinberg .SH COPYRIGHT 2022, Miguel Grinberg .\" Generated by docutils manpage writer. .