Adding authorization and authentication

Pyramid provides facilities for authentication and authorization. We will make use of both features to provide security to our application. Our application currently allows anyone with access to the server to view, edit, and add pages to our wiki. We will change that to allow only people who are members of a group named group:editors to add and edit wiki pages. We will continue to allow anyone with access to the server to view pages.

We will also add a login page and a logout link on all the pages. The login page will be shown when a user is denied access to any of the views that require permission, instead of a default "403 Forbidden" page.

We will implement the access control with the following steps:

  • Add password hashing dependencies.

  • Add users and groups (security.py, a new module).

  • Add a security policy (security.py).

  • Add an ACL (models.py).

  • Add permission declarations to the edit_page and add_page views (views.py).

Then we will add the login and logout features:

  • Add login and logout views (views.py).

  • Add a login template (login.pt).

  • Make the existing views return a logged_in flag to the renderer (views.py).

  • Add a "Logout" link to be shown when logged in and viewing or editing a page (view.pt, edit.pt).

Access control

Add dependencies

Just like in Defining Views, we need a new dependency. We need to add the bcrypt package to our tutorial package's setup.py file by assigning this dependency to the requires parameter in the setup() function.

Open setup.py and edit it to look like the following:

11requires = [
12    'bcrypt',
13    'docutils',
14    'plaster_pastedeploy',
15    'pyramid',
16    'pyramid_chameleon',
17    'pyramid_debugtoolbar',
18    'waitress',
19    'pyramid_retry',
20    'pyramid_tm',
21    'pyramid_zodbconn',
22    'transaction',
23    'ZODB',
24]
25
26tests_require = [
27    'WebTest',
28    'pytest',
29    'pytest-cov',
30]

Only the highlighted line needs to be added.

Do not forget to run pip install -e . just like in Running pip install -e ..

Note

We are using the bcrypt package from PyPI to hash our passwords securely. There are other one-way hash algorithms for passwords if bcrypt is an issue on your system. Just make sure that it is an algorithm approved for storing passwords versus a generic one-way hash.

Add the security policy

Create a new tutorial/security.py module with the following content:

 1import bcrypt
 2from pyramid.authentication import AuthTktCookieHelper
 3from pyramid.authorization import (
 4    ACLHelper,
 5    Authenticated,
 6    Everyone,
 7)
 8
 9
10def hash_password(pw):
11    hashed_pw = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
12    # return unicode instead of bytes because databases handle it better
13    return hashed_pw.decode('utf-8')
14
15def check_password(expected_hash, pw):
16    if expected_hash is not None:
17        return bcrypt.checkpw(pw.encode('utf-8'), expected_hash.encode('utf-8'))
18    return False
19
20USERS = {
21    'editor': hash_password('editor'),
22    'viewer': hash_password('viewer'),
23}
24GROUPS = {'editor': ['group:editors']}
25
26class MySecurityPolicy:
27    def __init__(self, secret):
28        self.authtkt = AuthTktCookieHelper(secret)
29        self.acl = ACLHelper()
30
31    def identity(self, request):
32        identity = self.authtkt.identify(request)
33        if identity is not None and identity['userid'] in USERS:
34            return identity
35
36    def authenticated_userid(self, request):
37        identity = self.identity(request)
38        if identity is not None:
39            return identity['userid']
40
41    def remember(self, request, userid, **kw):
42        return self.authtkt.remember(request, userid, **kw)
43
44    def forget(self, request, **kw):
45        return self.authtkt.forget(request, **kw)
46
47    def permits(self, request, context, permission):
48        principals = self.effective_principals(request)
49        return self.acl.permits(context, principals, permission)
50
51    def effective_principals(self, request):
52        principals = [Everyone]
53        identity = self.identity(request)
54        if identity is not None:
55            principals.append(Authenticated)
56            principals.append('u:' + identity['userid'])
57            principals.extend(GROUPS.get(identity['userid'], []))
58        return principals
59
60def includeme(config):
61    settings = config.get_settings()
62
63    config.set_security_policy(MySecurityPolicy(settings['auth.secret']))

Since we've added a new tutorial/security.py module, we need to include it. Open the file tutorial/__init__.py and edit the following lines:

 1from pyramid.config import Configurator
 2from pyramid_zodbconn import get_connection
 3
 4from .models import appmaker
 5
 6
 7def root_factory(request):
 8    conn = get_connection(request)
 9    return appmaker(conn.root())
10
11
12def main(global_config, **settings):
13    """ This function returns a Pyramid WSGI application.
14    """
15    with Configurator(settings=settings) as config:
16        config.include('pyramid_chameleon')
17        config.include('pyramid_tm')
18        config.include('pyramid_retry')
19        config.include('pyramid_zodbconn')
20        config.include('.routes')
21        config.include('.security')
22        config.set_root_factory(root_factory)
23        config.scan()
24    return config.make_wsgi_app()

The security policy controls several aspects of authentication and authorization:

  • Identifying the current user's identity for a request.

  • Authorizating access to resources.

  • Creating payloads for remembering and forgetting users.

Identifying logged-in users

The MySecurityPolicy.identity method inspects the request and determines if it came from an authenticated user. It does this by utilizing the pyramid.authentication.AuthTktCookieHelper class which stores the identity in a cryptographically-signed cookie. If a request does contain an identity, then we perform a final check to determine if the user is valid in our current USERS store.

Authorizing access to resources

The MySecurityPolicy.permits method determines if the request is allowed a specific permission on the given context. This process is done in a few steps:

  • Convert the request into a list of principals via the MySecurityPolicy.effective_principals method.

  • Compare the list of principals to the context using the pyramid.authorization.ACLHelper. It will only allow access if it can find an ACE that grants one of the principals the necessary permission.

For our application we've defined a list of a few principals:

Various wiki pages will grant some of these principals access to edit existing or add new pages.

Finally there are two helper methods that will help us to authenticate users. The first is hash_password which takes a raw password and transforms it using bcrypt into an irreversible representation, a process known as "hashing". The second method, check_password, will allow us to compare the hashed value of the submitted password against the hashed value of the password stored in the user's record. If the two hashed values match, then the submitted password is valid, and we can authenticate the user.

We hash passwords so that it is impossible to decrypt and use them to authenticate in the application. If we stored passwords foolishly in clear text, then anyone with access to the database could retrieve any password to authenticate as any user.

In a production system, user and group data will most often be saved and come from a database. Here we use "dummy" data to represent user and groups sources.

Add new settings

Our authentication policy is expecting a new setting, auth.secret. Open the file development.ini and add the highlighted line below:

19retry.attempts = 3
20
21auth.secret = seekrit

Best practices tell us to use a different secret in each environment. Open production.ini and add a different secret:

17retry.attempts = 3
18
19auth.secret = real-seekrit

Edit testing.ini to add its unique secret:

17retry.attempts = 3
18
19auth.secret = testing-seekrit

Add an ACL

Open tutorial/models/__init__.py and add the following import statement near the top:

3from pyramid.authorization import (
4    Allow,
5    Everyone,
6)

Add the following lines to the Wiki class:

 9class Wiki(PersistentMapping):
10    __name__ = None
11    __parent__ = None
12    __acl__ = [
13        (Allow, Everyone, 'view'),
14        (Allow, 'group:editors', 'edit'),
15    ]

We import Allow, an action which means that permission is allowed. We also import Everyone, a special principal that is associated to all requests. Both are used in the ACE entries that make up the ACL.

The ACL is a list that needs to be named __acl__ and be an attribute of a class. We define an ACL with two ACE entries. The first entry allows any user the view permission. The second entry allows the group:editors principal the edit permission.

The Wiki class that contains the ACL is the resource constructor for the root resource, which is a Wiki instance. The ACL is provided to each view in the context of the request as the context attribute.

It is only happenstance that we assigned this ACL at class scope. An ACL can be attached to an object instance too. This is how "row level security" can be achieved in Pyramid applications. We actually need only one ACL for the entire system, however, because our security requirements are simple, so this feature is not demonstrated.

See also

See Implementing ACL Authorization for more information about what an ACL represents.

Add permission declarations

Open tutorial/views/default.py. Add a permission='view' parameter to the @view_config decorators for view_wiki() and view_page() as follows:

12@view_config(context='..models.Wiki', permission='view')
17@view_config(context='..models.Page',
18             renderer='tutorial:templates/view.pt',
19             permission='view')

Only the highlighted lines, along with their preceding commas, need to be edited and added.

This allows anyone to invoke these two views.

Next add a permission='edit' parameter to the @view_config decorators for add_page() and edit_page():

39@view_config(name='add_page', context='..models.Wiki',
40             renderer='tutorial:templates/edit.pt',
41             permission='edit')
58@view_config(name='edit_page', context='..models.Page',
59             renderer='tutorial:templates/edit.pt',
60             permission='edit')

Only the highlighted lines, along with their preceding commas, need to be edited and added.

The result is that only users who possess the edit permission at the time of the request may invoke those two views.

We are done with the changes needed to control access. The changes that follow will add the login and logout feature.

Login, logout

Add login and logout views

We will add a login view which renders a login form and processes the post from the login form, checking credentials.

We will also add a logout view callable to our application and provide a link to it. This view will clear the credentials of the logged in user and redirect back to the front page.

Add a new file tutorial/views/auth.py with the following contents:

 1from pyramid.httpexceptions import HTTPSeeOther
 2from pyramid.security import (
 3    forget,
 4    remember,
 5)
 6from pyramid.view import (
 7    forbidden_view_config,
 8    view_config,
 9)
10
11from ..security import check_password, USERS
12
13
14@view_config(context='..models.Wiki', name='login',
15             renderer='tutorial:templates/login.pt')
16@forbidden_view_config(renderer='tutorial:templates/login.pt')
17def login(request):
18    login_url = request.resource_url(request.root, 'login')
19    referrer = request.url
20    if referrer == login_url:
21        referrer = '/'  # never use the login form itself as came_from
22    came_from = request.params.get('came_from', referrer)
23    message = ''
24    login = ''
25    password = ''
26    if 'form.submitted' in request.params:
27        login = request.params['login']
28        password = request.params['password']
29        if check_password(USERS.get(login), password):
30            headers = remember(request, login)
31            return HTTPSeeOther(location=came_from, headers=headers)
32        message = 'Failed login'
33        request.response.status = 400
34
35    return dict(
36        message=message,
37        url=login_url,
38        came_from=came_from,
39        login=login,
40        password=password,
41        title='Login',
42    )
43
44
45@view_config(context='..models.Wiki', name='logout')
46def logout(request):
47    headers = forget(request)
48    return HTTPSeeOther(
49        location=request.resource_url(request.context),
50        headers=headers,
51    )

forbidden_view_config() will be used to customize the default 403 Forbidden page. remember() and forget() help to create and expire an auth ticket cookie.

login() has two decorators:

  • A @view_config decorator which associates it with the login route and makes it visible when we visit /login.

  • A @forbidden_view_config decorator which turns it into a forbidden view. login() will be invoked when a user tries to execute a view callable for which they lack authorization. For example, if a user has not logged in and tries to add or edit a Wiki page, then they will be shown the login form before being allowed to continue.

The order of these two view configuration decorators is unimportant.

logout() is decorated with a @view_config decorator which associates it with the logout route. It will be invoked when we visit /logout.

Add the login.pt Template

Create tutorial/templates/login.pt with the following content:

<div metal:use-macro="load: layout.pt">
    <div metal:fill-slot="content">

        <div class="content">
              <p>
                <strong>
                  Login
                </strong><br>
                <span tal:replace="message"></span>
              </p>
              <form action="${url}" method="post">
                <input type="hidden" name="came_from" value="${came_from}">
                <div class="form-group">
                  <label for="login">Username</label>
                  <input type="text" name="login" value="${login}">
                </div>
                <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" name="password" value="${password}">
                </div>
                <div class="form-group">
                  <button type="submit" name="form.submitted" value="Log In" class="btn btn-default">Log In</button>
                </div>
              </form>
        </div>

    </div>
</div>

The above template is referenced in the login view that we just added in views.py.

Viewing the application in a browser

We can finally examine our application in a browser (See Start the application). Launch a browser and visit each of the following URLs, checking that the result is as expected:

  • http://localhost:6543/ invokes the view_wiki view. This always redirects to the view_page view of the FrontPage Page resource. It is executable by any user.

  • http://localhost:6543/login invokes the login view, and a login form will be displayed. On every page, there is a "Login" link in the upper right corner while the user is not authenticated, else it is a "Logout" link when the user is authenticated.

    Supplying the credentials with either the username editor and password editor will authenticate the user and grant access for that group.

    After logging in (as a result of hitting an edit or add page and submitting valid credentials), we will see a "Logout" link in the upper right hand corner. When we click it, we are logged out, redirected back to the front page, and a "Login" link is shown in the upper right hand corner.

  • http://localhost:6543/FrontPage invokes the view_page view of the FrontPage Page resource. This is because it is the default view (a view without a name) for Page resources. It is executable by any user.

  • http://localhost:6543/FrontPage/edit_page invokes the edit view for the FrontPage object. It is executable by only the editor user. If a different user (or the anonymous user) invokes it, then a login form will be displayed. The editor user will see the edit page form.

  • http://localhost:6543/add_page/SomePageName invokes the add view for a page. It is executable by only the editor user. If a different user (or the anonymous user) invokes it, a login form will be displayed. The editor user will see the edit page form.

  • To generate a not found error, visit http://localhost:6543/wakawaka which will invoke the notfound_view view provided by the cookiecutter.