The Passlib documentation has moved to https://passlib.readthedocs.io
passlib.apache - Apache Password Files¶
This module provides utilities for reading and writing Apache’s htpasswd and htdigest files; though the use of two helper classes.
Changed in version 1.6: The api for this module was updated to be more flexible, and to have less ambiguous method names. The old method and keyword names are deprecated, and will be removed in Passlib 1.8.
Changed in version 1.7: These classes will now preserve blank lines and “#” comments when updating htpasswd files; previous releases would throw a parse error.
Htpasswd Files¶
The HTpasswdFile class allows managing of htpasswd files.
A quick summary of its usage:
>>> from passlib.apache import HtpasswdFile
>>> # when creating a new file, set to new=True, add entries, and save.
>>> ht = HtpasswdFile("test.htpasswd", new=True)
>>> ht.set_password("someuser", "really secret password")
>>> ht.save()
>>> # loading an existing file to update a password
>>> ht = HtpasswdFile("test.htpasswd")
>>> ht.set_password("someuser", "new secret password")
>>> ht.save()
>>> # examining file, verifying user's password
>>> ht = HtpasswdFile("test.htpasswd")
>>> ht.users()
[ "someuser" ]
>>> ht.check_password("someuser", "wrong password")
False
>>> ht.check_password("someuser", "new secret password")
True
>>> # making in-memory changes and exporting to string
>>> ht = HtpasswdFile()
>>> ht.set_password("someuser", "mypass")
>>> ht.set_password("someuser", "anotherpass")
>>> print ht.to_string()
someuser:$apr1$T4f7D9ly$EobZDROnHblCNPCtrgh5i/
anotheruser:$apr1$vBdPWvh1$GrhfbyGvN/7HalW5cS9XB1
Warning
HtpasswdFile currently defaults to using apr_md5_crypt,
as this is the only htpasswd hash guaranteed to be portable across operating systems.
However, for security reasons Passlib 1.7 will default to using the strongest algorithm
available on the host platform (e.g. bcrypt or sha256_crypt).
Applications that are relying on the old behavior should specify
HtpasswdFile(default_scheme="portable") (new in Passlib 1.6.3).
-
class
passlib.apache.HtpasswdFile(path=None, new=False, autosave=False, ...)¶ class for reading & writing Htpasswd files.
The class constructor accepts the following arguments:
Parameters: - path (filepath) –
Specifies path to htpasswd file, use to implicitly load from and save to.
This class has two modes of operation:
- It can be “bound” to a local file by passing a
pathto the class constructor. In this case it will load the contents of the file when created, and theload()andsave()methods will automatically load from and save to that file if they are called without arguments. - Alternately, it can exist as an independant object, in which case
load()andsave()will require an explicit path to be provided whenever they are called. As well,autosavebehavior will not be available.This feature is new in Passlib 1.6, and is the default if no
pathvalue is provided to the constructor.
This is also exposed as a readonly instance attribute.
- It can be “bound” to a local file by passing a
- new (bool) –
Normally, if path is specified,
HtpasswdFilewill immediately load the contents of the file. However, when creating a new htpasswd file, applications can setnew=Trueso that the existing file (if any) will not be loaded.New in version 1.6: This feature was previously enabled by setting
autoload=False. That alias has been deprecated, and will be removed in Passlib 1.8 - autosave (bool) –
Normally, any changes made to an
HtpasswdFileinstance will not be saved untilsave()is explicitly called. However, ifautosave=Trueis specified, any changes made will be saved to disk immediately (assuming path has been set).This is also exposed as a writeable instance attribute.
- encoding (str) –
Optionally specify character encoding used to read/write file and hash passwords. Defaults to
utf-8, thoughlatin-1is the only other commonly encountered encoding.This is also exposed as a readonly instance attribute.
- default_scheme (str) –
Optionally specify default scheme to use when encoding new passwords.
This can be any of the schemes with builtin Apache support, OR natively supported by the host OS’s
crypt.crypt()function.- Builtin schemes include
"bcrypt"(apache 2.4+),"apr_md5_crypt"`, and ``"des_crypt". - Schemes commonly supported by Unix hosts
include
"bcrypt","sha256_crypt", and"des_crypt".
In order to not have to sort out what you should use, passlib offers a number of aliases, that will resolve to the most appropriate scheme based on your needs:
"portable","portable_apache_24"– pick scheme that’s portable across hosts running apache >= 2.4. This will be the default as of Passlib 2.0."portable_apache_22"– pick scheme that’s portable across hosts running apache >= 2.4. This is the default up to Passlib 1.9."host","host_apache_24"– pick strongest scheme supported by- apache >= 2.4 and/or host OS.
"host_apache_22"– pick strongest scheme supported by- apache >= 2.2 and/or host OS.
New in version 1.6: This keyword was previously named
default. That alias has been deprecated, and will be removed in Passlib 1.8.Changed in version 1.6.3: Added support for
"bcrypt","sha256_crypt", and"portable"alias.Changed in version 1.7: Added apache 2.4 semantics, and additional aliases.
- Builtin schemes include
- context (
CryptContext) –CryptContextinstance used to create and verify the hashes found in the htpasswd file. The default value is a pre-built context which supports all of the hashes officially allowed in an htpasswd file.This is also exposed as a readonly instance attribute.
Warning
This option may be used to add support for non-standard hash formats to an htpasswd file. However, the resulting file will probably not be usable by another application, and particularly not by Apache.
- autoload –
Set to
Falseto prevent the constructor from automatically loaded the file from disk.Deprecated since version 1.6: This has been replaced by the new keyword. Instead of setting
autoload=False, you should usenew=True. Support for this keyword will be removed in Passlib 1.8. - default –
Change the default algorithm used to hash new passwords.
Deprecated since version 1.6: This has been renamed to default_scheme for clarity. Support for this alias will be removed in Passlib 1.8.
Loading & Saving¶
-
load(path=None, force=True)¶ Load state from local file. If no path is specified, attempts to load from
self.path.Parameters: - path (str) – local file to load from
- force (bool) –
if
force=False, only load fromself.pathif file has changed since last load.Deprecated since version 1.6: This keyword will be removed in Passlib 1.8; Applications should use
load_if_changed()instead.
-
load_if_changed()¶ Reload from
self.pathonly if file has changed since last load
-
load_string(data)¶ Load state from unicode or bytes string, replacing current state
-
save(path=None)¶ Save current state to file. If no path is specified, attempts to save to
self.path.
-
to_string()¶ Export current state as a string of bytes
Inspection¶
-
users()¶ Return list of all users in database
-
check_password(user, password)¶ Verify password for specified user. If algorithm marked as deprecated by CryptContext, will automatically be re-hashed.
Returns: Noneif user not found.Falseif user found, but password does not match.Trueif user found and password matches.
Changed in version 1.6: This method was previously called
verify, it was renamed to prevent ambiguity with theCryptContextmethod. The old alias is deprecated, and will be removed in Passlib 1.8.
-
get_hash(user)¶ Return hash stored for user, or
Noneif user not found.Changed in version 1.6: This method was previously named
find, it was renamed for clarity. The old name is deprecated, and will be removed in Passlib 1.8.
Modification¶
-
set_password(user, password)¶ Set password for user; adds user if needed.
Returns: Trueif existing user was updated.Falseif user account was added.
Changed in version 1.6: This method was previously called
update, it was renamed to prevent ambiguity with the dictionary method. The old alias is deprecated, and will be removed in Passlib 1.8.
-
delete(user)¶ Delete user’s entry.
Returns: Trueif user deleted.Falseif user not found.
Alternate Constructors¶
-
from_string(data, **kwds)¶ create new object from raw string.
Parameters: - data (unicode or bytes) – database to load, as single string.
- **kwds – all other keywords are the same as in the class constructor
Attributes¶
-
path¶ Path to local file that will be used as the default for all
load()andsave()operations. May be written to, initialized by the path constructor keyword.
-
autosave¶ Writeable flag indicating whether changes will be automatically written to path.
Errors¶
Raises: ValueError – All of the methods in this class will raise a ValueErrorif any user name contains a forbidden character (one of:\r\n\t\x00), or is longer than 255 characters.- path (filepath) –
Htdigest Files¶
The HtdigestFile class allows management of htdigest files
in a similar fashion to HtpasswdFile.
-
class
passlib.apache.HtdigestFile(path, default_realm=None, new=False, autosave=False, ...)¶ class for reading & writing Htdigest files.
The class constructor accepts the following arguments:
Parameters: - path (filepath) –
Specifies path to htdigest file, use to implicitly load from and save to.
This class has two modes of operation:
- It can be “bound” to a local file by passing a
pathto the class constructor. In this case it will load the contents of the file when created, and theload()andsave()methods will automatically load from and save to that file if they are called without arguments. - Alternately, it can exist as an independant object, in which case
load()andsave()will require an explicit path to be provided whenever they are called. As well,autosavebehavior will not be available.This feature is new in Passlib 1.6, and is the default if no
pathvalue is provided to the constructor.
This is also exposed as a readonly instance attribute.
- It can be “bound” to a local file by passing a
- default_realm (str) –
If
default_realmis set, all theHtdigestFilemethods that require a realm will use this value if one is not provided explicitly. If unset, they will raise an error stating that an explicit realm is required.This is also exposed as a writeable instance attribute.
New in version 1.6.
- new (bool) –
Normally, if path is specified,
HtdigestFilewill immediately load the contents of the file. However, when creating a new htpasswd file, applications can setnew=Trueso that the existing file (if any) will not be loaded.New in version 1.6: This feature was previously enabled by setting
autoload=False. That alias has been deprecated, and will be removed in Passlib 1.8 - autosave (bool) –
Normally, any changes made to an
HtdigestFileinstance will not be saved untilsave()is explicitly called. However, ifautosave=Trueis specified, any changes made will be saved to disk immediately (assuming path has been set).This is also exposed as a writeable instance attribute.
- encoding (str) –
Optionally specify character encoding used to read/write file and hash passwords. Defaults to
utf-8, thoughlatin-1is the only other commonly encountered encoding.This is also exposed as a readonly instance attribute.
- autoload –
Set to
Falseto prevent the constructor from automatically loaded the file from disk.Deprecated since version 1.6: This has been replaced by the new keyword. Instead of setting
autoload=False, you should usenew=True. Support for this keyword will be removed in Passlib 1.8.
Loading & Saving¶
-
load(path=None, force=True)¶ Load state from local file. If no path is specified, attempts to load from
self.path.Parameters: - path (str) – local file to load from
- force (bool) –
if
force=False, only load fromself.pathif file has changed since last load.Deprecated since version 1.6: This keyword will be removed in Passlib 1.8; Applications should use
load_if_changed()instead.
-
load_if_changed()¶ Reload from
self.pathonly if file has changed since last load
-
load_string(data)¶ Load state from unicode or bytes string, replacing current state
-
save(path=None)¶ Save current state to file. If no path is specified, attempts to save to
self.path.
-
to_string()¶ Export current state as a string of bytes
Inspection¶
-
realms()¶ Return list of all realms in database
-
users(realm=None)¶ Return list of all users in specified realm.
- uses
self.default_realmif no realm explicitly provided. - returns empty list if realm not found.
- uses
-
check_password(user, [realm, ]password)¶ Verify password for specified user + realm.
If
self.default_realmhas been set, this may be called with the syntaxcheck_password(user, password), otherwise it must be called with all three arguments:check_password(user, realm, password).Returns: Noneif user or realm not found.Falseif user found, but password does not match.Trueif user found and password matches.
Changed in version 1.6: This method was previously called
verify, it was renamed to prevent ambiguity with theCryptContextmethod. The old alias is deprecated, and will be removed in Passlib 1.8.
-
get_hash(user, realm=None)¶ Return
htdigesthash stored for user.- uses
self.default_realmif no realm explicitly provided. - returns
Noneif user or realm not found.
Changed in version 1.6: This method was previously named
find, it was renamed for clarity. The old name is deprecated, and will be removed in Passlib 1.8.- uses
Modification¶
-
set_password(user, [realm, ]password)¶ Set password for user; adds user & realm if needed.
If
self.default_realmhas been set, this may be called with the syntaxset_password(user, password), otherwise it must be called with all three arguments:set_password(user, realm, password).Returns: Trueif existing user was updatedFalseif user account added.
-
delete(user, realm=None)¶ Delete user’s entry for specified realm.
if realm is not specified, uses
self.default_realm.Returns: Trueif user deleted,Falseif user not found in realm.
-
delete_realm(realm)¶ Delete all users for specified realm.
if realm is not specified, uses
self.default_realm.Returns: number of users deleted (0 if realm not found)
Alternate Constructors¶
-
from_string(data, **kwds)¶ create new object from raw string.
Parameters: - data (unicode or bytes) – database to load, as single string.
- **kwds – all other keywords are the same as in the class constructor
Attributes¶
-
default_realm¶ The default realm that will be used if one is not provided to methods that require it. By default this is
None, in which case an explicit realm must be provided for every method call. Can be written to.
-
path¶ Path to local file that will be used as the default for all
load()andsave()operations. May be written to, initialized by the path constructor keyword.
-
autosave¶ Writeable flag indicating whether changes will be automatically written to path.
Errors¶
Raises: ValueError – All of the methods in this class will raise a ValueErrorif any user name or realm contains a forbidden character (one of:\r\n\t\x00), or is longer than 255 characters.- path (filepath) –
Footnotes
| [1] | Htpasswd Manual - http://httpd.apache.org/docs/current/programs/htpasswd.html |
| [2] | Apache Auth Configuration - http://httpd.apache.org/docs/current/howto/auth.html |