Skip to main content

FastAPI Bearer Auth

A simple FastAPI auth module implementing OAuth2 with Password (and hashing), Bearer with JWT tokens, including user signup, signin routes.

Installing

Works on python3.6+

pip install fastapi-bearer-auth

Example of using

from fastapi import Depends, FastAPI
from pydantic import BaseModel

import fastapi_bearer_auth as fba


class UserOut(BaseModel):
    username: str


app = FastAPI(title='Test App')
# simple in-memory db
users = {}


# Two required handler: handle_get_user_by_name and handle_create_user
@fba.handle_get_user_by_name  # type: ignore
async def get_user_by_name(name, **extra_fields):
    return users.get(name)


@fba.handle_create_user  # type: ignore
async def create_user(username, password, **extra_fields):
    if await get_user_by_name(username):
        raise ValueError('User {} exists'.format(username))
    user = {
        'username': username,
        'password': await fba.call_config('get_password_hash', password),
        **extra_fields,
    }
    users[username] = user
    return user


# Three router depends available: fba.signup, fba.signin and fba.get_current_user
# fba.signup resolve to User object
@app.post('/user/signup', response_model=UserOut)
async def signup(user=Depends(fba.signup)):
    return user


# fba.signin resolve to {user: <user_object>, token: {token_type, access_token}}
@app.post('/user/signin')
async def signin(ret=Depends(fba.signin)):
    return ret['token']


@app.post('/user/signup-with-json')
async def signup_with_json(
    user=Depends(fba.action('signup', method='json', username_field='email')),
):
    return user


@app.post('/user/signin-with-json')
async def signin_with_json(
    ret=Depends(fba.action('signin', method='json', username_field='email')),
):
    return ret['token']


@app.post('/user/signup-with-extra-fields')
async def signup_with_extra_fields(
    user=Depends(fba.action('signup', method='json', extra_fields=['email'])),
):
    return user


# fba.get_current_user resolve to User object or a HTTP 401 response
@app.get('/user/me')
async def me(user=Depends(fba.get_current_user)):
    return user

Now head to http://127.0.0.1:8000/docs to test the API. Note the me route, using fba.get_current_user dependency to restrict resource for authenticated user.

There's a simple command to achive this without writing any code:

uvicorn fastapi_bearer_auth.test:app

Customize

In addition to get_user_by_name(name) and create_user(username, password), there're other functions can be override (with handle_ prefix):

  • authenticate(username, password)
  • verify_password(plain_password, hashed_password)
  • get_password_hash(password)

You can call all those functions with fba.call_config(name, *args, **kwargs).

Also some params:

  • ACCESS_TOKEN_EXPIRE_MINUTES
  • ALGORITHM
  • SECRET_KEY

Use something like fba.set_config({'SECRET_KEY': 'xxx', ...}) to change it.

The default tokenUrl for openapi docs is user/signin, you can override this by setting env var TOKEN_URL.

Metadata

Release files for fastapi-bearer-auth 0.1.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-bearer-auth 0.1.8
File Size Uploaded Provenance
fastapi_bearer_auth-0.1.8.tar.gz 5.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-bearer-auth 0.1.8
File Interpreter ABI Platform
fastapi_bearer_auth-0.1.8-py3-none-any.whl Python 3 none any Details

Total release size: 14.0 kB

Release files / fastapi_bearer_auth-0.1.8.tar.gz

Download URL fastapi_bearer_auth-0.1.8.tar.gz
Size 5.6 kB
Tags Source
SHA-256 checksum
How to use checksums
90016c8fb4e07c80f7db294d13b744a7242107d32b9c52b2b0cb530a07508dc5
BLAKE2b-256 checksum
How to use checksums
df1ff125c069f52a8d7d53a08337fe9405ef687be94d1f8e7dbb6bd7bc2ba391
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.12.7 Linux/5.15.167.4-microsoft-standard-WSL2

Release files / fastapi_bearer_auth-0.1.8-py3-none-any.whl

Download URL fastapi_bearer_auth-0.1.8-py3-none-any.whl
Size 8.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f4c8ad908dc74e919f58a43fbff571af586475fc9b5fc5c4e084e013cd56b226
BLAKE2b-256 checksum
How to use checksums
a6c36e68ba2a2590674365e276a0f20c2e6f6097604c8bf2f09af8689fcec7eb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.12.7 Linux/5.15.167.4-microsoft-standard-WSL2

Security for fastapi-bearer-auth 0.1.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page