An authorization middleware for FastAPI that supports ACL, RBAC, ABAC, based on PyCasbin
Project description
fastapi-authz
fastapi-authz is an authorization middleware for FastAPI, it's based on PyCasbin.
Installation
Install from pip
pip install fastapi-authz
Clone this repo
git clone https://github.com/pycasbin/fastapi-authz.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_authz 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.
Development
Run unit tests
- Fork/Clone repository
- Install fastapi-authz 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:
subject
: the logged-in user nameobject
: the URL path for the web resource likedataset1/item1
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file fastapi-authz-0.1.0.tar.gz
.
File metadata
- Download URL: fastapi-authz-0.1.0.tar.gz
- Upload date:
- Size: 8.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 52c51184b60bee25501178b419b23c31007b6b4b6ba8940908d7f9a252f669de |
|
MD5 | 09029a6f43180cd3660000bf7be8f8f2 |
|
BLAKE2b-256 | effb11538a3ff6c41077ceba2eac1c09a22b33a2fd486c0b85d6199537c31f61 |
File details
Details for the file fastapi_authz-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: fastapi_authz-0.1.0-py3-none-any.whl
- Upload date:
- Size: 10.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7dc70d67f97a78fc795a2f62797d9e04aaa7bf8786fbb696d4487dac9cc19b35 |
|
MD5 | 9717e4bdc9d86c264bf3be7e580a454c |
|
BLAKE2b-256 | caeca00a111fbaee811f40b03f77b5630a2035f9637bff3a0c7b9a3b9826db3a |