Skip to main content

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.

Metadata

Release files for fastapi-casbin-auth 1.5.0

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-casbin-auth 1.5.0
File Size Uploaded
fastapi_casbin_auth-1.5.0.tar.gz 9.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-casbin-auth 1.5.0
File Interpreter ABI Platform
fastapi_casbin_auth-1.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 21.0 kB

Release files / fastapi_casbin_auth-1.5.0.tar.gz

Download URL fastapi_casbin_auth-1.5.0.tar.gz
Size 9.5 kB
Tags Source
SHA-256 checksum
How to use checksums
da586aca4e948db70c7613bd5b32a32b9e0385a6abccfe24ea96fa5106aae8b4
BLAKE2b-256 checksum
How to use checksums
ea778c02d741dfdc9337331b05aaaf940b7020c3192673e5d2312aaeade3ae72
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release files / fastapi_casbin_auth-1.5.0-py3-none-any.whl

Download URL fastapi_casbin_auth-1.5.0-py3-none-any.whl
Size 11.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
993b9bdc7f8a584d84db2f2a3ff127fe3d2af487431371bc06f872194f5900d9
BLAKE2b-256 checksum
How to use checksums
8e34d9ea21a8d9fb931f431ae47cc64698396144d87c772daa7346dd07d10c13
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release history Release notifications | RSS feed

This release

1.5.0 This release

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

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