Skip to main content

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:

Authentication diagram

Token update 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

connectkit_fastapi_authentication-2.3.0.tar.gz (30.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file connectkit_fastapi_authentication-2.3.0.tar.gz.

File metadata

File hashes

Hashes for connectkit_fastapi_authentication-2.3.0.tar.gz
Algorithm Hash digest
SHA256 081d3a94c2db7986b70c694c28d5fdc95e28e6131e99acc3e76f24e205021e90
MD5 4259a1fd43026c65ac3e8f3044af9675
BLAKE2b-256 595a164a4a4df8558307628202cd97722802f7dafb17642fc205e25a3e3a71e5

See more details on using hashes here.

File details

Details for the file connectkit_fastapi_authentication-2.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for connectkit_fastapi_authentication-2.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f5ebf7b482a29e72a765825135bd34015cd93a869eaef25f046e976b6b236b17
MD5 1620715d60c677098c813c87e44ac037
BLAKE2b-256 469f337832811dafdd5121bedcaffddabd55f32de48a9c7a8983f56bf6707cd6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page