Pyramid provides an optional declarative authorization system that can prevent a view from being invoked based on an authorization policy. Before a view is invoked, the authorization system can use the credentials in the request along with the context resource to determine if access will be allowed. Here's how it works at a high level:
- A request is generated when a user visits the application.
- Based on the request, a context resource is located through resource location. A context is located differently depending on whether the application uses traversal or URL dispatch, but a context is ultimately found in either case. See the URL Dispatch chapter for more information.
- A view callable is located by view lookup using the context as well as other attributes of the request.
- If an authentication policy is in effect, it is passed the request; it returns some number of principal identifiers.
- If an authorization policy is in effect and the view configuration associated with the view callable that was found has a permission associated with it, the authorization policy is passed the context, some number of principal identifiers returned by the authentication policy, and the permission associated with the view; it will allow or deny access.
- If the authorization policy allows access, the view callable is invoked.
- If the authorization policy denies access, the view callable is not invoked; instead the forbidden view is invoked.
Security in Pyramid, unlike many systems, cleanly and explicitly separates authentication and authorization. Authentication is merely the mechanism by which credentials provided in the request are resolved to one or more principal identifiers. These identifiers represent the users and groups in effect during the request. Authorization then determines access based on the principal identifiers, the view callable being invoked, and the context resource.
Authorization is enabled by modifying your application to include an authentication policy and authorization policy. Pyramid comes with a variety of implementations of these policies. To provide maximal flexibility, Pyramid also allows you to create custom authentication policies and authorization policies.
Protecting Views with Permissions¶
To protect a view callable from invocation based on a user's security settings when a particular type of resource becomes the context, you must pass a permission to view configuration. Permissions are usually just strings, and they have no required composition: you can name permissions whatever you like.
For example, the following view declaration protects the view named
add_entry.html when the context resource is of type
Blog with the
add permission using the
1 2 3 4 5 6
# config is an instance of pyramid.config.Configurator config.add_view('mypackage.views.blog_entry_add_view', name='add_entry.html', context='mypackage.resources.Blog', permission='add')
The equivalent view registration including the
add permission name
may be performed via the
1 2 3 4 5 6 7
from pyramid.view import view_config from resources import Blog @view_config(context=Blog, name='add_entry.html', permission='add') def blog_entry_add_view(request): """ Add blog entry code goes here """ pass
As a result of any of these various view configuration statements, if an
authorization policy is in place when the view callable is found during
normal application operations, the requesting user will need to possess the
add permission against the context resource in order to be able
to invoke the
blog_entry_add_view view. If he does not, the
Forbidden view will be invoked.
Setting a Default Permission¶
If a permission is not supplied to a view configuration, the registered view will always be executable by entirely anonymous users: any authorization policy in effect is ignored.
In support of making it easier to configure applications which are
"secure by default", Pyramid allows you to configure a
default permission. If supplied, the default permission is used as
the permission string to all view registrations which don't otherwise
supports configuring a default permission for an application.
When a default permission is registered:
- If a view configuration names an explicit
permission, the default permission is ignored for that view registration, and the view-configuration-named permission is used.
- If a view configuration names the permission
pyramid.security.NO_PERMISSION_REQUIRED, the default permission is ignored, and the view is registered without a permission (making it available to all callers regardless of their credentials).
Assigning ACLs to your Resource Objects¶
When the default Pyramid authorization policy determines
whether a user possesses a particular permission with respect to a resource,
it examines the ACL associated with the resource. An ACL is
associated with a resource by adding an
__acl__ attribute to the resource
object. This attribute can be defined on the resource instance if you need
instance-level security, or it can be defined on the resource class if you
just need type-level security.
For example, an ACL might be attached to the resource for a blog via its class:
1 2 3 4 5 6 7 8 9
from pyramid.security import Allow from pyramid.security import Everyone class Blog(object): __acl__ = [ (Allow, Everyone, 'view'), (Allow, 'group:editors', 'add'), (Allow, 'group:editors', 'edit'), ]
Or, if your resources are persistent, an ACL might be specified via the
__acl__ attribute of an instance of a resource:
1 2 3 4 5 6 7 8 9 10 11 12 13
from pyramid.security import Allow from pyramid.security import Everyone class Blog(object): pass blog = Blog() blog.__acl__ = [ (Allow, Everyone, 'view'), (Allow, 'group:editors', 'add'), (Allow, 'group:editors', 'edit'), ]
Whether an ACL is attached to a resource's class or an instance of the resource itself, the effect is the same. It is useful to decorate individual resource instances with an ACL (as opposed to just decorating their class) in applications such as "CMS" systems where fine-grained access is required on an object-by-object basis.
Dynamic ACLs are also possible by turning the ACL into a callable on the resource. This may allow the ACL to dynamically generate rules based on properties of the instance.
1 2 3 4 5 6 7 8 9 10 11 12 13
from pyramid.security import Allow from pyramid.security import Everyone class Blog(object): def __acl__(self): return [ (Allow, Everyone, 'view'), (Allow, self.owner, 'edit'), (Allow, 'group:editors', 'edit'), ] def __init__(self, owner): self.owner = owner
Elements of an ACL¶
Here's an example ACL:
1 2 3 4 5 6 7 8
from pyramid.security import Allow from pyramid.security import Everyone __acl__ = [ (Allow, Everyone, 'view'), (Allow, 'group:editors', 'add'), (Allow, 'group:editors', 'edit'), ]
The example ACL indicates that the
pyramid.security.Everyone principal -- a special
system-defined principal indicating, literally, everyone -- is allowed
to view the blog, the
group:editors principal is allowed to add to
and edit the blog.
Each element of an ACL is an ACE or access control entry.
For example, in the above code block, there are three ACEs:
(Allow, 'group:editors', 'add'), and
(Allow, 'group:editors', 'edit').
The first element of any ACE is either
pyramid.security.Deny, representing the action to take when
the ACE matches. The second element is a principal. The
third argument is a permission or sequence of permission names.
A principal is usually a user id, however it also may be a group id if your
authentication system provides group information and the effective
authentication policy policy is written to respect group information.
For example, the
pyramid.authentication.RepozeWho1AuthenticationPolicy respects group
information if you configure it with a
Each ACE in an ACL is processed by an authorization policy in the order dictated by the ACL. So if you have an ACL like this:
1 2 3 4 5 6 7 8
from pyramid.security import Allow from pyramid.security import Deny from pyramid.security import Everyone __acl__ = [ (Allow, Everyone, 'view'), (Deny, Everyone, 'view'), ]
The default authorization policy will allow everyone the view permission, even though later in the ACL you have an ACE that denies everyone the view permission. On the other hand, if you have an ACL like this:
1 2 3 4 5 6 7 8
from pyramid.security import Everyone from pyramid.security import Allow from pyramid.security import Deny __acl__ = [ (Deny, Everyone, 'view'), (Allow, Everyone, 'view'), ]
The authorization policy will deny everyone the view permission, even though later in the ACL is an ACE that allows everyone.
The third argument in an ACE can also be a sequence of permission
names instead of a single permission name. So instead of creating
multiple ACEs representing a number of different permission grants to
group:editors group, we can collapse this into a single
ACE, as below.
1 2 3 4 5 6 7
from pyramid.security import Allow from pyramid.security import Everyone __acl__ = [ (Allow, Everyone, 'view'), (Allow, 'group:editors', ('add', 'edit')), ]
Special Principal Names¶
Literally, everyone, no matter what. This object is actually a string "under the hood" (
system.Everyone). Every user "is" the principal named Everyone during every request, even if a security policy is not in use.
Any user with credentials as determined by the current security policy. You might think of it as any user that is "logged in". This object is actually a string "under the hood" (
Special permission names exist in the
module. These can be imported for use in ACLs.
An object representing, literally, all permissions. Useful in an ACL like so:
(Allow, 'fred', ALL_PERMISSIONS). The
ALL_PERMISSIONSobject is actually a stand-in object that has a
__contains__method that always returns
True, which, for all known authorization policies, has the effect of indicating that a given principal "has" any permission asked for by the system.
A convenience ACE is defined representing a deny to everyone of all
pyramid.security.DENY_ALL. This ACE is often used as
the last ACE of an ACL to explicitly cause inheriting authorization
policies to "stop looking up the traversal tree" (effectively breaking any
inheritance). For example, an ACL which allows only
fred the view
permission for a particular resource despite what inherited ACLs may say when
the default authorization policy is in effect might look like so:
1 2 3 4
from pyramid.security import Allow from pyramid.security import DENY_ALL __acl__ = [ (Allow, 'fred', 'view'), DENY_ALL ]
"Under the hood", the
pyramid.security.DENY_ALL ACE equals
from pyramid.security import ALL_PERMISSIONS __acl__ = [ (Deny, Everyone, ALL_PERMISSIONS) ]
ACL Inheritance and Location-Awareness¶
While the default authorization policy is in place, if a resource object does not have an ACL when it is the context, its parent is consulted for an ACL. If that object does not have an ACL, its parent is consulted for an ACL, ad infinitum, until we've reached the root and there are no more parents left.
In order to allow the security machinery to perform ACL inheritance, resource
objects must provide location-awareness. Providing location-awareness
means two things: the root object in the resource tree must have a
__name__ attribute and a
1 2 3
class Blog(object): __name__ = '' __parent__ = None
An object with a
__parent__ attribute and a
is said to be location-aware. Location-aware objects define an
__parent__ attribute which points at their parent object. The
See also pyramid.location for documentations of functions which use location-awareness.
See also Location-Aware Resources.
Changing the Forbidden View¶
When Pyramid denies a view invocation due to an
authorization denial, the special
forbidden view is invoked. "Out
of the box", this forbidden view is very plain. See
Changing the Forbidden View within Using Hooks for
instructions on how to create a custom forbidden view and arrange for
it to be called when view authorization is denied.
Creating Your Own Authentication Policy¶
Pyramid ships with a number of useful out-of-the-box
security policies (see
creating your own authentication policy is often necessary when you
want to control the "horizontal and vertical" of how your users
authenticate. Doing so is a matter of creating an instance of something
that implements the following interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
class IAuthenticationPolicy(object): """ An object representing a Pyramid authentication policy. """ def authenticated_userid(self, request): """ Return the authenticated userid or ``None`` if no authenticated userid can be found. This method of the policy should ensure that a record exists in whatever persistent store is used related to the user (the user should not have been deleted); if a record associated with the current id does not exist in a persistent store, it should return ``None``.""" def unauthenticated_userid(self, request): """ Return the *unauthenticated* userid. This method performs the same duty as ``authenticated_userid`` but is permitted to return the userid based only on data present in the request; it needn't (and shouldn't) check any persistent store to ensure that the user record related to the request userid exists.""" def effective_principals(self, request): """ Return a sequence representing the effective principals including the userid and any groups belonged to by the current user, including 'system' groups such as ``pyramid.security.Everyone`` and ``pyramid.security.Authenticated``. """ def remember(self, request, principal, **kw): """ Return a set of headers suitable for 'remembering' the principal named ``principal`` when set in a response. An individual authentication policy and its consumers can decide on the composition and meaning of **kw. """ def forget(self, request): """ Return a set of headers suitable for 'forgetting' the current user on subsequent requests. """
After you do so, you can pass an instance of such a class into the
configuration time to use it.
Admonishment Against Secret-Sharing¶
A "secret" is required by various components of Pyramid. For example, the
authentication policy below uses a secret value
authn_policy = AuthTktAuthenticationPolicy('seekrit', hashalg='sha512')
A session factory also requires a secret:
my_session_factory = SignedCookieSessionFactory('itsaseekreet')
It is tempting to use the same secret for multiple Pyramid subsystems. For
example, you might be tempted to use the value
seekrit as the secret for
both the authentication policy and the session factory defined above. This is
a bad idea, because in both cases, these secrets are used to sign the payload
of the data.
If you use the same secret for two different parts of your application for signing purposes, it may allow an attacker to get his chosen plaintext signed, which would allow the attacker to control the content of the payload. Re-using a secret across two different subsystems might drop the security of signing to zero. Keys should not be re-used across different contexts where an attacker has the possibility of providing a chosen plaintext.