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:

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

tests_require = [
    'WebTest',
    'pytest',
    'pytest-cov',
]

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:

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import bcrypt
from pyramid.authentication import AuthTktCookieHelper
from pyramid.authorization import (
    ACLHelper,
    Authenticated,
    Everyone,
)


def hash_password(pw):
    hashed_pw = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
    # return unicode instead of bytes because databases handle it better
    return hashed_pw.decode('utf-8')

def check_password(expected_hash, pw):
    if expected_hash is not None:
        return bcrypt.checkpw(pw.encode('utf-8'), expected_hash.encode('utf-8'))
    return False

USERS = {
    'editor': hash_password('editor'),
    'viewer': hash_password('viewer'),
}
GROUPS = {'editor': ['group:editors']}

class MySecurityPolicy:
    def __init__(self, secret):
        self.authtkt = AuthTktCookieHelper(secret)
        self.acl = ACLHelper()

    def authenticated_identity(self, request):
        identity = self.authtkt.identify(request)
        if identity is not None and identity['userid'] in USERS:
            return identity

    def authenticated_userid(self, request):
        identity = self.authenticated_identity(request)
        if identity is not None:
            return identity['userid']

    def remember(self, request, userid, **kw):
        return self.authtkt.remember(request, userid, **kw)

    def forget(self, request, **kw):
        return self.authtkt.forget(request, **kw)

    def permits(self, request, context, permission):
        principals = self.effective_principals(request)
        return self.acl.permits(context, principals, permission)

    def effective_principals(self, request):
        principals = [Everyone]
        identity = self.authenticated_identity(request)
        if identity is not None:
            principals.append(Authenticated)
            principals.append('u:' + identity['userid'])
            principals.extend(GROUPS.get(identity['userid'], []))
        return principals

def includeme(config):
    settings = config.get_settings()

    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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from pyramid.config import Configurator
from pyramid_zodbconn import get_connection

from .models import appmaker


def root_factory(request):
    conn = get_connection(request)
    return appmaker(conn.root())


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    with Configurator(settings=settings) as config:
        config.include('pyramid_chameleon')
        config.include('pyramid_tm')
        config.include('pyramid_retry')
        config.include('pyramid_zodbconn')
        config.include('.routes')
        config.include('.security')
        config.set_root_factory(root_factory)
        config.scan()
    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.authenticated_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:

19
20
21
retry.attempts = 3

auth.secret = seekrit

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

17
18
19
retry.attempts = 3

auth.secret = real-seekrit

Edit testing.ini to add its unique secret:

17
18
19
retry.attempts = 3

auth.secret = testing-seekrit

Add an ACL

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

4
5
6
7
    Allow,
    Everyone,
)

Add the following lines to the Wiki class:

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

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
18
19
@view_config(context='..models.Page',
             renderer='tutorial:templates/view.pt',
             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
40
41
@view_config(name='add_page', context='..models.Wiki',
             renderer='tutorial:templates/edit.pt',
             permission='edit')
58
59
60
@view_config(name='edit_page', context='..models.Page',
             renderer='tutorial:templates/edit.pt',
             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:

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
    forget,
    remember,
)
from pyramid.view import (
    forbidden_view_config,
    view_config,
)

from ..security import check_password, USERS


@view_config(context='..models.Wiki', name='login',
             renderer='tutorial:templates/login.pt')
@forbidden_view_config(renderer='tutorial:templates/login.pt')
def login(request):
    login_url = request.resource_url(request.root, 'login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/'  # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = ''
    password = ''
    if 'form.submitted' in request.params:
        login = request.params['login']
        password = request.params['password']
        if check_password(USERS.get(login), password):
            headers = remember(request, login)
            return HTTPSeeOther(location=came_from, headers=headers)
        message = 'Failed login'
        request.response.status = 400

    return dict(
        message=message,
        url=login_url,
        came_from=came_from,
        login=login,
        password=password,
        title='Login',
    )


@view_config(context='..models.Wiki', name='logout')
def logout(request):
    headers = forget(request)
    return HTTPSeeOther(
        location=request.resource_url(request.context),
        headers=headers,
    )

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/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. Supplying the credentials with the username editor and password editor will display 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. Supplying the credentials with the username editor, password editor will display the edit page form.
  • After logging in (as a result of hitting an edit or add page and submitting the login form with the editor credentials), we will see a Logout link in the upper right hand corner. When we click it, we are logged out, and redirected back to the front page.
  • To generate a not found error, visit http://localhost:6543/wakawaka which will invoke the notfound_view view provided by the cookiecutter.