Package: aiohttp_auth_autz
aiohttp_auth_autzThis library provides authorization and authentication middleware plugins for
aiohttp servers.These plugins are designed to be lightweight, simple, and extensible, allowing
the library to be reused regardless of the backend authentication mechanism.
This provides a familiar framework across projects.There are three middleware plugins provided by the library. Theauth_middlewareplugin provides a simple system for authenticating a users credentials, and
ensuring that the user is who they say they are.Theautz_middlewareplugin provides a generic way of authorization using
different authorization policies. There is the ACL authorization policy as a
part of the plugin.Theacl_middlewareplugin provides a simple access control list authorization
mechanism, where users are provided access to different view handlers depending
on what groups the user is a member of. It is recomended to useautz_middlewarewith ACL policy instead of this middleware.This is a fork ofaiohttp_authlibrary that fixes some bugs and security issues and also introduces a generic
authorizationautzmiddleware with built in ACL authorization policy.Documentationhttp://aiohttp-auth-autz.readthedocs.io/InstallInstallaiohttp_auth_autzusingpip:$ pip install aiohttp_auth_autzGetting StartedA simple example how to use authentication and authorization middleware
with an aiohttp application.importasynciofromosimporturandomimportaiohttp_authfromaiohttpimportwebfromaiohttp_authimportauth,autzfromaiohttp_auth.authimportauth_requiredfromaiohttp_auth.autzimportautz_requiredfromaiohttp_auth.autz.policyimportaclfromaiohttp_auth.permissionsimportPermission,Groupdb={'bob':{'password':'bob_password','groups':['guest','staff']},'alice':{'password':'alice_password','groups':['guest']}}# global ACL contextcontext=[(Permission.Allow,'guest',{'view',}),(Permission.Deny,'guest',{'edit',}),(Permission.Allow,'staff',{'view','edit','admin_view'}),(Permission.Allow,Group.Everyone,{'view_home',})]# create an ACL authorization policy classclassACLAutzPolicy(acl.AbstractACLAutzPolicy):"""The concrete ACL authorization policy."""def__init__(self,db,context=None):# do not forget to call parent __init__super().__init__(context)self.db=dbasyncdefacl_groups(self,user_identity):"""Return acl groups for given user identity.

        This method should return a sequence of groups for given user_identity.

        Args:
            user_identity: User identity returned by auth.get_auth.

        Returns:
            Sequence of acl groups for the user identity.
        """# implement application specific logic hereuser=self.db.get(user_identity,None)ifuserisNone:# return empty tuple in order to give a chance# to Group.Everyonereturntuple()returnuser['groups']asyncdeflogin(request):# http://127.0.0.1:8080/login?username=bob&password=bob_passworduser_identity=request.GET.get('username',None)password=request.GET.get('password',None)ifuser_identityindbandpassword==db[user_identity]['password']:# remember user identityawaitauth.remember(request,user_identity)returnweb.Response(text='Ok')raiseweb.HTTPUnauthorized()# only authenticated users can logout# if user is not authenticated auth_required decorator# will raise a web.HTTPUnauthorized@auth_requiredasyncdeflogout(request):# forget user identityawaitauth.forget(request)returnweb.Response(text='Ok')# user should have a group with 'admin_view' permission allowed# if he does not autz_required will raise a web.HTTPForbidden@autz_required('admin_view')asyncdefadmin(request):returnweb.Response(text='Admin Page')@autz_required('view_home')asyncdefhome(request):text='Home page.'# check if current user is permitted with 'admin_view' permissionifawaitautz.permit(request,'admin_view'):text+=' Admin page: http://127.0.0.1:8080/admin'# get current user identityuser_identity=awaitauth.get_auth(request)ifuser_identityisnotNone:# user is authenticatedtext+=' Logout: http://127.0.0.1:8080/logout'returnweb.Response(text=text)# decorators can work with class based viewsclassMyView(web.View):"""Class based view."""@autz_required('view')asyncdefget(self):# example of permit usingifawaitautz.permit(self.request,'view'):returnweb.Response(text='View Page')returnweb.Response(text='View is not permitted')definit_app(loop):app=web.Application()# Create an auth ticket mechanism that expires after 1 minute (60# seconds), and has a randomly generated secret. Also includes the# optional inclusion of the users IP address in the hashauth_policy=auth.CookieTktAuthentication(urandom(32),60,include_ip=True)# Create an ACL authorization policyautz_policy=ACLAutzPolicy(db,context)# setup middlewares in aiohttp fashionaiohttp_auth.setup(app,auth_policy,autz_policy)app.router.add_get('/',home)app.router.add_get('/login',login)app.router.add_get('/logout',logout)app.router.add_get('/admin',admin)app.router.add_route('*','/view',MyView)returnapploop=asyncio.get_event_loop()app=init_app(loop)web.run_app(app,host='127.0.0.1',loop=loop)LicenseThe library is licensed under a MIT license.Changelog0.2.2 (2017-04-18)Move toaiohttp2.x.Add support of middlewares decorators foraiohttp.web.Viewhandlers.Adduvloopas IO loop for tests.0.2.1 (2017-02-16)autzmiddleware:Simplifyaclauthorization policy by moving permit logic intopolicy.acl.AbstractACLAutzPolicy.Removepolicy.acl.AbstractACLContextclass.Removepolicy.acl.NaiveACLContextclass.Removepolicy.acl.ACLContextclass.0.2.0 (2017-02-14)aclmiddleware:Addsetupfunction foraclmiddleware to install it in aiohttp fashion.Fix bug inacl_requireddecorator.Fix a possible security issue withaclgroups. The issue is follow: the default behavior is
to adduser_idto groups for authenticated users by the acl middleware, but ifuser_idis equal to some of acl groups that user suddenly has the permissions he is not
allowed for. So to avoid this kind of issueuser_idis not added to groups any more.IntroduceAbstractACLGroupsCallbackclass inaclmiddleware to make it possible easily create
callable object by inheriting from the abstract class and implementingacl_groupsmethod. It
can be useful to store additional information (such database connection etc.) within such class.
An instance of this subclass can be used in place ofacl_groups_callbackparameter.authmiddleware:Addsetupfunction forauthmiddleware to install it in aiohttp fashion.auth.auth_requiredraised now aweb.HTTPUnauthorizedinstead of aweb.HTTPForbidden.Introduce generic authorization middlewareautzthat performs authorization through the same
interface (autz.permitcoroutine andautz_requireddecorator) but using different policies.
Middleware has the ACL authorization as the built in policy which works in the same way asaclmiddleware. Users are free to add their own custom policies or to modify ACL one.Add globalaiohttp_auth.setupfunction to installauthandautzmiddlewares at once
in aiohttp fashion.Add docs.Rewrite tests usingpytestandpytest-aiohttp.