Skip to main content

API key-based security for FastAPI using SQLModel

Project description

FastAPI Simple Security via SQLModel

codecov Python Tests Linting

Ruff Code style: black pre-commit enabled Conventional Commits

(This is forked from FastAPI Simple Security with an SQLModel adaption. Credits to the original author!)

API key based security package for FastAPI, focused on simplicity of use:

  • Full functionality out of the box, no configuration required
  • API key security with local sqlite backend, working with both header and query parameters
  • Default 15 days deprecation for generated API keys
  • Key creation, revocation, renewing, and usage logs handled through administrator endpoints
  • No dependencies, only requiring FastAPI and the python standard library

This module cannot be used for any kind of distributed deployment. It's goal is to help have some basic security features for simple one-server API deployments, mostly during development.

Installation

pip install fastapi_sqlmodel_security

Usage

Creating an application

The key is to configure an instance of data store, which can usually be done with SqlModelDataStore as shown below.

from fastapi_sqlmodel_security import create_auth_router, ApiKeySecurity, DataStore, SqlModelDataStore
from fastapi import Depends, FastAPI

app = FastAPI()

data_store = SqlModelDataStore(conn_url="sqlite3:///keys.db")

app.include_router(create_auth_router(data_store), prefix="/auth", tags=["_auth"])

@app.get("/secure", dependencies=[Depends(ApiKeySecurity(data_store))])
async def secure_endpoint():
    return {"message": "This is a secure endpoint"}

Both the auth router and your own routes would need dependencies to be configured with the aforementioned data store.

Resulting app is:

app

More can be found in the demo app.

API key creation through docs

Start your API and check the logs for the automatically generated secret key if you did not provide one through environment variables.

secret

Go to /docs on your API and inform this secret key in the Authorize/Secret header box. All the administrator endpoints only support header security to make sure the secret key is not inadvertently shared when sharing an URL.

secret_header

Then, you can use /auth/new to generate a new API key.

api key

And finally, you can use this API key to access the secure endpoint.

secure endpoint

API key creation in python

You can of course automate API key acquisition through python with requests and directly querying the endpoints.

If you do so, you can hide the endpoints from your API documentation with the environment variable FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS.

Testing

You may want to use a no-auth api key security filter NoAuthApiKeySecurity as an alternative to the real filter.

It does not do any key verification and will never block any requests, as long as they carry an API key of any value.

Configuration

Environment variables:

  • FASTAPI_SQLMODEL_SECURITY_SECRET: Secret administrator key

    • Generated automatically on server startup if not provided
    • Allows generation of new API keys, revoking of existing ones, and API key usage view
    • It being compromised compromises the security of the API
  • FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS: Whether or not to hide the API key related endpoints from the documentation

  • FASTAPI_SQLMODEL_SECURITY_AUTOMATIC_EXPIRATION: Duration, in days, until an API key is deemed expired

    • 15 days by default

Contributing

Setting up python environment

poetry install
poetry shell

Setting up pre-commit hooks

pre-commit install

Running tests

pytest

Running the dev environment

The attached docker image runs a test app on localhost:8080 with secret key TEST_SECRET. Run it with:

docker-compose build && docker-compose up

Needed contributions

  • More options with sensible defaults
  • Logging per API key?
  • More back-end options for API key storage?

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

fastapi_sqlmodel_security-1.0.1.tar.gz (7.0 kB view details)

Uploaded Source

Built Distribution

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

fastapi_sqlmodel_security-1.0.1-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_sqlmodel_security-1.0.1.tar.gz.

File metadata

  • Download URL: fastapi_sqlmodel_security-1.0.1.tar.gz
  • Upload date:
  • Size: 7.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.4.2 CPython/3.11.7 Linux/6.2.0-1018-azure

File hashes

Hashes for fastapi_sqlmodel_security-1.0.1.tar.gz
Algorithm Hash digest
SHA256 025f2f150cc3a1218258b9620b2d9ac95e6aae62a4a2280a0d41cdf8644efea2
MD5 13b7b42c9a77c52593e8d32c0422db70
BLAKE2b-256 bfe7599d5c734d1e1706ded1299a7b1d1715564b84631b68f80cbc54a1298ff3

See more details on using hashes here.

File details

Details for the file fastapi_sqlmodel_security-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_sqlmodel_security-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f03cfefa4a0ad412b0c8abb8798636903b14e06999aff8aef0b6101c934f02b5
MD5 ef1b5f88a6b49f7707c67bbdd5afa560
BLAKE2b-256 6903716ea6fd428c5a0a3e1101eae23789df1ffc8ceec076a4699fd9b3f86feb

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