Authorization Middleware API¶
Setup auth and autz¶
-
aiohttp_auth.setup(app, auth_policy, autz_policy)¶ Setup auth and autz middleware in aiohttp fashion.
Parameters: - app – aiohttp Application object.
- auth_policy – An authentication policy with a base class of AbstractAuthentication.
- autz_policy – An authorization policy with a base class of AbstractAutzPolicy
Public Middleware API¶
Authorization middleware.
-
aiohttp_auth.autz.autz.setup(app, autz_policy)¶ Setup an authorization middleware in
aiohttpfashion.Note that
aiohttp_auth.authmiddleware should be installed too to useautzmiddleware. So the preferred way to install this middleware is to use globalaiohttp_auth.setupfunction.Parameters: - app – aiohttp
Applicationobject. - autz_policy – A subclass of
aiohttp_auth.autz.abc.AbstractAutzPolicy.
- app – aiohttp
-
aiohttp_auth.autz.autz.autz_middleware(autz_policy)¶ Return authorization middleware factory.
Return
aiohttp_auth.autzmiddleware factory for use by theaiohttpapplication object. This middleware can be used only withaiohttp_auth.authmiddleware installed.The
autzmiddleware provides follow interface to use in applications:- Using
autz.permitcoroutine. - Using
autz.autz_requireddecorator foraiohttphandlers.
Note that the recomended way to initialize this middleware is through
aiohttp_auth.autz.setuporaiohttp_auth.setupfunctions. As theautzmiddleware can be used only with authenticationaiohttp_auth.authmiddleware it is preferred to useaiohttp_auth.setup.Parameters: autz_policy – a subclass of aiohttp_auth.autz.abc.AbstractAutzPolicy.Returns: An aiohttpmiddleware factory.- Using
-
aiohttp_auth.autz.autz.permit(request, permission, context=None)¶ Check if permission is allowed for given request with given context.
The authorization checking is provided by authorization policy which is set by setup function. The nature of permission and context is also determined by the given policy.
Note that this coroutine uses
aiohttp_auth.auth.get_authcoroutine to determineuser_identityfor given request. So that middleware should be installed too.Note that some additional exceptions could be raised by certain policy while checking the permission.
Parameters: - request – aiohttp
Requestobject. - permission – The specific permission requested.
- context – A context provided for checking permissions. Could be optional if authorization policy provides a way to specify a global application context.
Returns: Trueif permission is allowedFalseotherwise.Raises: RuntimeError– Ifauthorautzmiddleware is not installed.- request – aiohttp
Decorators¶
Authorization decorators.
-
aiohttp_auth.autz.decorators.autz_required(permission, context=None)¶ Create decorator to check if user has requested permission.
This function constructs a decorator that can be used to check a aiohttp’s view for authorization before calling it. It uses the
autz.permitfunction to check the request against the passed permission and context. If the user does not have the correct permission to run this function, it raisesweb.HTTPForbidden.Note that context can be optional if authorization policy provides a way to specify global application context. Also context parameter can be used to override global context if it is provided by authorization policy.
Note that some exceptions could be raised by certain policy while checking the permission.
Parameters: - permission – The specific permission requested.
- context – A context provided for checking permissions. Could be optional if authorization policy provides a way to specify a global application context.
Returns: A decorator which will check the request passed has the permission for the given context. The decorator will raise
web.HTTPForbiddenif the user does not have the correct permissions to access the view.
ACL Authorization Policy¶
ACL authorization policy.
This module introduces AbstractACLAutzPolicy - an abstract base class to
create ACL authorization policy class. The subclass should define how to
retrieve user’s groups.
-
class
aiohttp_auth.autz.policy.acl.AbstractACLAutzPolicy(context=None)¶ Abstract base class for ACL authorization policy.
As the library does not know how to get groups for user and it is always up to application, it provides abstract authorization ACL policy class. Subclass should implement
acl_groupsmethod to use it withautz_middleware.Note that an ACL context can be specified globally while initializing policy or locally through
autz.permitfunction’s parameter. A local context will always override a global one while checking permissions. If there is no local context and global context is not set then thepermitmethod will raise aRuntimeError.A context is a sequence of ACL tuples which consist of an
Allow/Denyaction, a group, and a set of permissions for that ACL group. For example:context = [(Permission.Allow, 'view_group', {'view', }), (Permission.Allow, 'edit_group', {'view', 'edit'}),]
ACL tuple sequences are checked in order, with the first tuple that matches the group the user is a member of, and includes the permission passed to the function, to be the matching ACL group. If no ACL group is found, the
permitmethod returnsFalse.Groups and permissions need only be immutable objects, so can be strings, numbers, enumerations, or other immutable objects.
Note
Groups that are returned by
acl_groups(if they are notNone) will then be extended internally withGroup.EveryoneandGroup.AuthenticatedUser.Usage example:
from aiohttp import web from aiohttp_auth import autz from aiohttp_auth.autz import autz_required from aiohttp_auth.autz.policy import acl from aiohttp_auth.permissions import Permission class ACLAutzPolicy(acl.AbstractACLAutzPolicy): def __init__(self, users, context=None): super().__init__(context) # we will retrieve groups using some kind of users dict # here you can use db or cache or any other needed data self.users = users async def acl_groups(self, user_identity): # implement application specific logic here user = self.users.get(user_identity, None) if user is None: return None return user['groups'] def init(loop): app = web.Application(loop=loop) ... # here you need to initialize aiohttp_auth.auth middleware ... users = ... # Create application global context. # It can be overridden in autz.permit fucntion or in # autz_required decorator using local context explicitly. context = [(Permission.Allow, 'view_group', {'view', }), (Permission.Allow, 'edit_group', {'view', 'edit'})] autz.setup(app, ACLAutzPolicy(users, context)) # authorization using autz decorator applying to app request handler @autz_required('view') async def handler_view(request): # authorization using permit if await autz.permit(request, 'edit'): pass
-
__init__(context=None)¶ Initialize ACL authorization policy.
Parameters: context – global ACL context, default to None. Should be a list of ACL rules.
-
acl_groups(user_identity)¶ Return ACL groups for given user identity.
Subclass should implement this method to return a sequence of groups for given
user_identity.Parameters: user_identity – User identity returned by auth.get_auth.Returns: Sequence of ACL groups for the user identity (could be empty to give a chance to Group.EveryoneandGroup.AuthenticatedUser) orNone(permitwill always returnFalse).
-
permit(user_identity, permission, context=None)¶ Check if user is allowed for given permission with given context.
Parameters: - user_identity – Identity of the user returned by
aiohttp_auth.auth.get_authfunction - permission – The specific permission requested.
- context – A context provided for checking permissions. Could be optional if a global context is specified through policy initialization.
Returns: Trueif permission is allowed,Falseotherwise.Raises: RuntimeError– If there is neither global context nor local one.- user_identity – Identity of the user returned by
-