Authentication backends and helpers for Starlette-based apps and frameworks
Project description
starlette-auth-toolkit
Authentication backends and helpers for Starlette-based apps and frameworks.
Note: documentation is in progress — in the meantime, feel free to read the source code!
Contents
Installation
pip install starlette-auth-toolkit
Note: you need to install Starlette yourself.
Base backends
Base backends implement an authentication flow, but the exact implementation of credentials verification is left up to you. This means you can choose to perform a database query, use environment variables or private files, etc.
These backends grant a set of scopes when authentication succeeds.
Base backends are user model agnostic, although we recommend you implement the interface specified by starlette.authentication.BaseUser
(see also Starlette authentication).
They are available at starlette_auth_toolkit.base.backends
.
BasicAuthBackend
Implementation of the Basic authentication scheme.
Request header format
Authorization: Basic {credentials}
where {credentials}
refers to the base64 encoding of {username}:{password}
.
Example
# myapp/auth.py
from starlette.authentication import SimpleUser # or a custom user model
from starlette_auth_toolkit.base import backends
class BasicAuthBackend(backends.BasicAuthBackend):
async def verify(self, username: str, password: str):
# In practice, request the database to find the user associated
# to `username`, and validate that its password hash matches the
# given password.
if (username, password) != ("bob", "s3kr3t"):
return None
return SimpleUser(username)
Abstract methods
-
.verify(self, username: str, password: str) -> Optional[BaseUser]
If
username
andpassword
are valid, return the corresponding user. Otherwise, returnNone
.
Scopes
authenticated
BearerAuthBackend
Implementation of the Bearer authentication scheme.
Note: this is sometimes also referred to as "Token authentication".
Request header format
Authorization: Bearer {token}
Example
# myapp/auth.py
from starlette.authentication import SimpleUser # or a custom user model
from starlette_auth_toolkit.base import backends
class BearerAuthBackend(backends.BearerAuthBackend):
async def verify(self, token: str):
# In practice, request the database to find the token object
# associated to `token`, and return its associated user.
if token != "abcd":
return None
return SimpleUser("bob")
Abstract methods
-
.verify(self, token: str) -> Optional[BaseUser]
If
token
refers to a valid token, return the corresponding user. Otherwise, returnNone
.
Scopes
authenticated
Password hashers
This package provides password hashing utilities built on top of Passlib.
Usage
- Asynchronous:
await .make()
/await .verify()
(hashing and verification occurs in the threadpool)
import asyncio
from starlette_auth_toolkit.passwords import PBKDF2Hasher
async def main():
# Instanciate a hasher:
hasher = PBKDF2Hasher()
# Hash a password:
pwd = await hasher.make("hello")
# Verify a password against a known hash:
assert await hasher.verify("hello", pwd)
# Python 3.7+
asyncio.run(main())
- Blocking:
.make_sync()
/.verify_sync()
from starlette_auth_toolkit.passwords import PBKDF2Hasher
# Instanciate a hasher:
hasher = PBKDF2Hasher()
# Hash a password
pwd = hasher.make_sync("hello")
# Verify a password against a known hash:
assert hasher.verify_sync("hello", pwd)
Hash migration (Advanced)
If you need to change the hash algorithm (say from PBKDF2 to Argon2), you will typically want to keep support for existing hashes, but rehash them with the new algorithm as soon as possible.
MultiHasher
was designed to solve this problem:
from starlette_auth_toolkit.passwords import Argon2Hasher, PBKDF2Hasher, MultiHasher
hasher = MultiHasher([Argon2Hasher(), PBKDF2Hasher()])
The above hasher
will use Argon2 when hashing new passwords, but will be able to verify hashes created using either Argon2 or PBKDF2.
To detect whether a hash needs rehashing, use .needs_update()
:
valid = await hasher.verify(pwd, pwd_hash)
if hasher.needs_update(pwd_hash):
new_hash = await hasher.make(pwd)
# TODO: store new hash
# ...
Note: calling
.needs_update()
at anytime other than just after calling.verify()
will raise aRuntimeError
.
Available hashers
Name | Requires |
---|---|
PBKDF2Hasher |
|
CryptHasher |
|
BCryptHasher |
bcrypt |
Argon2Hasher |
argon2-cffi |
For advanced use cases, use Hasher
and pass one of the algorithms listed in passlib.hash:
from starlette_auth_toolkit.passwords import Hasher
hasher = Hasher(algorithm="pbkdf2_sha512")
Contributing
Want to contribute? Awesome! Be sure to read our Contributing guidelines.
Changelog
See CHANGELOG.md.
License
MIT
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file starlette-auth-toolkit-0.3.0.tar.gz
.
File metadata
- Download URL: starlette-auth-toolkit-0.3.0.tar.gz
- Upload date:
- Size: 7.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bb851f4312a384c4b417c3a69cc27dc7d6bc0f5d22ca1d18c9433abc1975ab5a |
|
MD5 | a0dd5dbe81141e42d955665a67dbdada |
|
BLAKE2b-256 | 022cd5e8981390d4eeecec95cb18bc443d22de1afce9d537fe1e2362aa69178d |
File details
Details for the file starlette_auth_toolkit-0.3.0-py3-none-any.whl
.
File metadata
- Download URL: starlette_auth_toolkit-0.3.0-py3-none-any.whl
- Upload date:
- Size: 8.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | dbb5939df9637d536ce2b62f0b43145139a2492061ee00be7630334b91979f84 |
|
MD5 | f80531cba5d599efad81f5bc45e9d00a |
|
BLAKE2b-256 | 7bfe294ebfbd1132a5b35d4617292582cde0b200eb02baf61d4143971bf77bea |