Package: fastapi-authz
fastapi-authzfastapi-authz is an authorization middleware forFastAPI, it's based
onPyCasbin.InstallationInstall from pippipinstallfastapi-authzClone this repogitclonehttps://github.com/pycasbin/fastapi-authz.git
pythonsetup.pyinstallQuickstartThis middleware is designed to work with another middleware which implementAuthenticationMiddlewareinterface.importbase64importbinasciiimportcasbinfromfastapiimportFastAPIfromstarlette.authenticationimportAuthenticationBackend,AuthenticationError,SimpleUser,AuthCredentialsfromstarlette.middleware.authenticationimportAuthenticationMiddlewarefromfastapi_authzimportCasbinMiddlewareapp=FastAPI()classBasicAuth(AuthenticationBackend):asyncdefauthenticate(self,request):if"Authorization"notinrequest.headers:returnNoneauth=request.headers["Authorization"]try:scheme,credentials=auth.split()decoded=base64.b64decode(credentials).decode("ascii")except(ValueError,UnicodeDecodeError,binascii.Error):raiseAuthenticationError("Invalid basic auth credentials")username,_,password=decoded.partition(":")returnAuthCredentials(["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('/')asyncdefindex():return"If you see this, you have been authenticated."@app.get('/dataset1/protected')asyncdefauth_test():return"You must be alice to see this."anonymous requestcurl-ihttp://127.0.0.1:8000/dataset1/protectedHTTP/1.1403Forbidden
date:Mon,01Mar202109:00:08GMT
server:uvicorn
content-length:11content-type:application/json"Forbidden"authenticated requestcurl-i-ualice:passwordhttp://127.0.0.1:8000/dataset1/protectedHTTP/1.1200OK
date:Mon,01Mar202109:04:54GMT
server:uvicorn
content-length:32content-type:application/json"You must be alice to see this."It used the casbin config fromexamplesfolder, and you can find this demo indemofolder.You can also view the unit tests to understand this middleware.Besides, there is another example forCasbinMiddlewarewhich is designed to work with JWT authentication. You can find
it indemo/jwt_test.py.DevelopmentRun unit testsFork/Clone repositoryInstall fastapi-authz dependencies, and runpytestpipinstall-rdev_requirements.txt
pipinstall-rrequirements.txt
pytestUpdate requirements with pip-tools# update requirements.txtpip-compile--no-annotate--no-header--rebuildrequirements.in# sync venvpip-syncManually Bump Versionbumpversion major  # major release
or
bumpversion minor  # minor release
or
bumpversion patch  # hotfix releaseDocumentationThe authorization determines a request based on{subject, object, action}, which means whatsubjectcan perform
whatactionon whatobject. In this plugin, the meanings are:subject: the logged-in user nameobject: the URL path for the web resource likedataset1/item1action: 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
tothe Casbin's documentation.Getting HelpCasbinLicenseThis project is under Apache 2.0 License. See theLICENSEfile for the full license text.