Skip to main content

An authorization middleware for FastAPI that supports ACL, RBAC, ABAC, based on PyCasbin

Project description

fastapi-casbin-auth

Build Status Coverage Status Version PyPI - Wheel Pyversions Download Discord

fastapi-casbin-auth is an authorization middleware for FastAPI, it's based on PyCasbin.

Installation

Install from pip

pip install fastapi-casbin-auth

Clone this repo

git clone https://github.com/officialpycasbin/fastapi-casbin-auth.git
python setup.py install

Quickstart

This middleware is designed to work with another middleware which implement AuthenticationMiddleware interface.

import base64
import binascii

import casbin

from fastapi import FastAPI
from starlette.authentication import AuthenticationBackend, AuthenticationError, SimpleUser, AuthCredentials
from starlette.middleware.authentication import AuthenticationMiddleware

from fastapi_casbin_auth import CasbinMiddleware

app = FastAPI()


class BasicAuth(AuthenticationBackend):
    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return None

        auth = request.headers["Authorization"]
        try:
            scheme, credentials = auth.split()
            decoded = base64.b64decode(credentials).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error):
            raise AuthenticationError("Invalid basic auth credentials")

        username, _, password = decoded.partition(":")
        return AuthCredentials(["authenticated"]), SimpleUser(username)


enforcer = casbin.Enforcer('../examples/rbac_model.conf', '../examples/rbac_policy.csv')

app.add_middleware(CasbinMiddleware, enforcer=enforcer)
app.add_middleware(AuthenticationMiddleware, backend=BasicAuth())


@app.get('/')
async def index():
    return "If you see this, you have been authenticated."


@app.get('/dataset1/protected')
async def auth_test():
    return "You must be alice to see this."
  • anonymous request
curl -i http://127.0.0.1:8000/dataset1/protected
HTTP/1.1 403 Forbidden
date: Mon, 01 Mar 2021 09:00:08 GMT
server: uvicorn
content-length: 11
content-type: application/json

"Forbidden"
  • authenticated request
curl -i -u alice:password http://127.0.0.1:8000/dataset1/protected
HTTP/1.1 200 OK
date: Mon, 01 Mar 2021 09:04:54 GMT
server: uvicorn
content-length: 32
content-type: application/json

"You must be alice to see this."

It used the casbin config from examples folder, and you can find this demo in demo folder.

You can also view the unit tests to understand this middleware.

Besides, there is another example for CasbinMiddleware which is designed to work with JWT authentication. You can find it in demo/jwt_test.py.

Development

Run unit tests

  1. Fork/Clone repository
  2. Install fastapi-casbin-auth dependencies, and run pytest
pip install -r dev_requirements.txt
pip install -r requirements.txt
pytest

Update requirements with pip-tools

# update requirements.txt
pip-compile --no-annotate --no-header --rebuild requirements.in
# sync venv
pip-sync

Manually Bump Version

bumpversion major  # major release
or
bumpversion minor  # minor release
or
bumpversion patch  # hotfix release

Documentation

The authorization determines a request based on {subject, object, action}, which means what subject can perform what action on what object. In this plugin, the meanings are:

  1. subject: the logged-in user name
  2. object: the URL path for the web resource like dataset1/item1
  3. action: HTTP method like GET, POST, PUT, DELETE, or the high-level actions you defined like "read-file", " write-blog" (currently no official support in this middleware)

For how to write authorization policy and other details, please refer to the Casbin's documentation.

Getting Help

License

This project is under Apache 2.0 License. See the LICENSE file for the full license text.

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_casbin_auth-1.1.0.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

fastapi_casbin_auth-1.1.0-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_casbin_auth-1.1.0.tar.gz.

File metadata

  • Download URL: fastapi_casbin_auth-1.1.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for fastapi_casbin_auth-1.1.0.tar.gz
Algorithm Hash digest
SHA256 dd7269ee701c63b384256c7bdc17c7a04905e2d8e3c15ea2ce263a848e4c2f1e
MD5 53c026cb37598e53e08a4cb05feed7ff
BLAKE2b-256 0f95f53a9b697d665bff1a84b7367d1a947608852402358cf04ef31ad2532ea3

See more details on using hashes here.

File details

Details for the file fastapi_casbin_auth-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_casbin_auth-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fb356e4f426e495132069dfe0d55a00d079b1f5dce90eb53ce1fbc8654e4c87d
MD5 9c8de32dab5abda69fe4b181f7c5f944
BLAKE2b-256 a7ce4c9d8c38ac54ac8db8925cd22642e24a132feb29a996576adea8b51b67f1

See more details on using hashes here.

Supported by

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