User accounts and jwt authentication for FastAPI services
Project description
ConnectKit FastAPI Authentication [en|ru]
ConnectKit FastAPI Authentication adds accounts, user sessions, and a user authentication mechanism using JWT for FastAPI applications.
Logging in via oauth2 or OpenID connect is not supported at the moment.
Not fully tested version
Installation
pip install ConnectKit-FastAPI-Authentication
Usage
Configuration parameters are loaded from environment variables, and can be redefined later.
secret: str | None = None
"""
Secret for signing access/refresh tokens.
Used for signing access/refresh user tokens, if None, random token will be generated on init module.
Default: None
"""
secret_algorithm: SecretAlgorithm = SecretAlgorithm.HS256
"""
Algorithm used for signing access/refresh tokens.
Available algorithms: HS256, HS512.
Default: HS256
"""
secret_store: SecretStore = SecretStore.COOKIE
# Issuer for inner tokens and otp installer
issuer: str = "Localhost inc."
# Lifetime of inner access token in minutes. Must be smaller
access_lifetime: int = Field(default=5, gt=0, le=30)
# Lifetime of inner short refresh token in hours. (Without "remember me" option)
refresh_lifetime_short: int = Field(default=24, gt=0, le=72)
# Lifetime of inner long refresh token in days. (With "remember me" option)
refresh_lifetime_long: int = Field(default=30, gt=0)
# Lifetime of password confirmation in minutes.
password_confirm_lifetime: int = Field(default=30, ge=5, le=1440)
# Name of access token cookie. In header mode used for identity anon users sessions (maybe lost).
cookie_name: str = "access"
# Protected URL path. (Protected path, basically api of app, exclude SPA pages)
# Note: cookie also bind for this path on top-level domain by browser
secure_path: str = "/api"
# Set up cookie only on https (TLS protected connection)
cookie_secure: bool = True
# Wrong password attempts before block account. If 0 protection disabled.
login_attempt_count: int = 5
# Wrong password attempts on protected routes before block account. If 0 protection disabled.
confirm_attempt_count: int = 0
#
otp_attempt_count: int = 5
# Enabled options for login (login field exists always, but can be disabled for login purposes)
user_login_properties: list[Literal['login', 'email', 'phone']] = ['login']
# Save user events history (update password/email/phone, success/failed login, success/failed checks, etc.)
user_save_history: bool = False # TODO
user_history_events: list[str] = []
# Use the scope model
user_has_scope: bool = False
Settings loaded from .env in pwd or from environ and can't be redefined later.
To set up a database connection.
To enable authorization endpoints and middleware:
from fastapi import FastAPI
from authentication import setup_app
app = FastAPI()
setup_app(app)
To require auth or anon use decorators:
from fastapi import APIRouter, Request
from authentication import (anonymous, authenticated, any_scopes, all_scopes,
AnonymousCredentials, AnonymousUser,
AuthenticatedCredentials, AuthenticatedUser)
from authentication import responses, common
from authentication.models import Account, AccountSession
router = APIRouter()
@router.get("/test", responses=common.responses(
responses.unauthorized, responses.access_timeout
))
@authenticated()
async def test(request: Request):
assert request.auth.is_authenticated
assert request.user.is_authenticated
creds: AuthenticatedCredentials = request.auth
user: AuthenticatedUser = request.user
@router.get("/test2", responses=common.responses(
responses.already_authenticated
))
@anonymous
async def test2(request: Request):
assert request.auth.is_anonymous
assert request.user.is_anonymous
creds: AnonymousCredentials = request.auth
user: AnonymousUser = request.user
@router.get("/test3", responses=common.responses(
responses.already_authenticated
))
async def test3(request: Request):
try:
a = request.auth.is_anonymous
b = request.user.is_anonymous
except Exception:
# Exception("Trying use authenticate for unsecured path. (Check settings of module)")
pass
The anonymous function decorator checks for anonymous user.
The authenticated function decorator checks for authenticated user.
The any_scopes function decorator checks for authenticated user with any subset of required scopes
(if scopes enabled in settings).
The all_scopes function decorator checks for authenticated user with all the required scopes
(if scopes enabled in settings).
To implement the registration form, manually add users and administrative work:
Authentication diagram:
Token update diagram:
License
ConnectKit FastAPIAuthentication is MIT License.
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file connectkit_fastapi_authentication-2.3.0.tar.gz.
File metadata
- Download URL: connectkit_fastapi_authentication-2.3.0.tar.gz
- Upload date:
- Size: 30.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.21.0 CPython/3.10.11 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
081d3a94c2db7986b70c694c28d5fdc95e28e6131e99acc3e76f24e205021e90
|
|
| MD5 |
4259a1fd43026c65ac3e8f3044af9675
|
|
| BLAKE2b-256 |
595a164a4a4df8558307628202cd97722802f7dafb17642fc205e25a3e3a71e5
|
File details
Details for the file connectkit_fastapi_authentication-2.3.0-py3-none-any.whl.
File metadata
- Download URL: connectkit_fastapi_authentication-2.3.0-py3-none-any.whl
- Upload date:
- Size: 35.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.21.0 CPython/3.10.11 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f5ebf7b482a29e72a765825135bd34015cd93a869eaef25f046e976b6b236b17
|
|
| MD5 |
1620715d60c677098c813c87e44ac037
|
|
| BLAKE2b-256 |
469f337832811dafdd5121bedcaffddabd55f32de48a9c7a8983f56bf6707cd6
|