Adding authentication

Pyramid provides facilities for authentication and authorization. In this section we'll focus solely on the authentication APIs to add login and logout functionality to our wiki.

We will implement authentication with the following steps:

  • Add a security policy (security.py).

  • Add routes for /login and /logout (routes.py).

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

  • Add a login template (login.jinja2).

  • Add "Login" and "Logout" links to every page based on the user's authenticated state (layout.jinja2).

  • Make the existing views verify user state (views/default.py).

  • Redirect to /login when a user is not logged in and is denied access to any of the views that require permission (views/auth.py).

  • Show a custom "403 Forbidden" page if a logged in user is denied access to any views that require permission (views/auth.py).

Authenticating requests

The core of Pyramid authentication is a security policy which is used to identify authentication information from a request, as well as handling the low-level login and logout operations required to track users across requests (via cookies, headers, or whatever else you can imagine).

Add the security policy

Update tutorial/security.py with the following content:

 1from pyramid.authentication import AuthTktCookieHelper
 2from pyramid.csrf import CookieCSRFStoragePolicy
 3from pyramid.request import RequestLocalCache
 4
 5from . import models
 6
 7
 8class MySecurityPolicy:
 9    def __init__(self, secret):
10        self.authtkt = AuthTktCookieHelper(secret)
11        self.identity_cache = RequestLocalCache(self.load_identity)
12
13    def load_identity(self, request):
14        identity = self.authtkt.identify(request)
15        if identity is None:
16            return None
17
18        userid = identity['userid']
19        user = request.dbsession.query(models.User).get(userid)
20        return user
21
22    def identity(self, request):
23        return self.identity_cache.get_or_create(request)
24
25    def authenticated_userid(self, request):
26        user = self.identity(request)
27        if user is not None:
28            return user.id
29
30    def remember(self, request, userid, **kw):
31        return self.authtkt.remember(request, userid, **kw)
32
33    def forget(self, request, **kw):
34        return self.authtkt.forget(request, **kw)
35
36def includeme(config):
37    settings = config.get_settings()
38
39    config.set_csrf_storage_policy(CookieCSRFStoragePolicy())
40    config.set_default_csrf_options(require_csrf=True)
41
42    config.set_security_policy(MySecurityPolicy(settings['auth.secret']))

Here we've defined a new security policy named MySecurityPolicy, which is implementing most of the pyramid.interfaces.ISecurityPolicy interface by tracking an identity using a signed cookie implemented by pyramid.authentication.AuthTktCookieHelper (lines 8-34). The security policy outputs the authenticated tutorial.models.User object for the logged-in user as the identity, which is available as request.identity.

Our new security policy defines how our application will remember, forget, and identify users. It also handles authorization, which we'll cover in the next chapter (if you're wondering why we didn't implement the permits method yet).

Identifying the current user is done in a few steps:

  1. Pyramid invokes a method on the policy requesting identity, userid, or permission to perform an operation.

  2. The policy starts by calling pyramid.request.RequestLocalCache.get_or_create() to load the identity.

  3. The MySecurityPolicy.load_identity method asks the cookie helper to pull the identity from the request. This value is None if the cookie is missing or the content cannot be verified.

  4. The policy then translates the identity into a tutorial.models.User object by looking for a record in the database. This is a good spot to confirm that the user is actually allowed to access our application. For example, maybe they were marked deleted or banned and we should return None instead of the user object.

  5. The result is stored in the identity_cache which ensures that subsequent invocations return the same identity object for the request.

Finally, pyramid.request.Request.identity contains either None or a tutorial.models.User instance.

Note the usage of the identity_cache is optional, but it has several advantages in most scenarios:

  • It improves performance as the identity is necessary for many operations during the lifetime of a request.

  • It provides consistency across method invocations to ensure the identity does not change while processing the request.

It is up to individual security policies and applications to determine the best approach with respect to caching. Applications with long-running requests may want to avoid caching the identity, or tracking some extra metadata to re-verify it periodically against the authentication source.

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

Finally, best practices tell us to use a different secret in each environment, so open production.ini and add a different secret:

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

And testing.ini:

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

Add permission checks

Pyramid has full support for declarative authorization, which we'll cover in the next chapter. However, many people looking to get their feet wet are just interested in authentication with some basic form of home-grown authorization. We'll show below how to accomplish the simple security goals of our wiki, now that we can track the logged-in state of users.

Remember our goals:

  • Allow only editor and basic logged-in users to create new pages.

  • Only allow editor users and the page creator (possibly a basic user) to edit pages.

Open the file tutorial/views/default.py and fix the following import:

3from pyramid.httpexceptions import (
4    HTTPForbidden,
5    HTTPNotFound,
6    HTTPSeeOther,
7)

Insert the highlighted line.

In the same file, now edit the edit_page view function:

44@view_config(route_name='edit_page', renderer='tutorial:templates/edit.jinja2')
45def edit_page(request):
46    pagename = request.matchdict['pagename']
47    page = request.dbsession.query(models.Page).filter_by(name=pagename).one()
48    user = request.identity
49    if user is None or (user.role != 'editor' and page.creator != user):
50        raise HTTPForbidden
51    if request.method == 'POST':
52        page.data = request.params['body']
53        next_url = request.route_url('view_page', pagename=page.name)
54        return HTTPSeeOther(location=next_url)
55    return dict(
56        pagename=page.name,
57        pagedata=page.data,
58        save_url=request.route_url('edit_page', pagename=page.name),
59    )

Only the highlighted lines need to be changed.

If the user either is not logged in or the user is not the page's creator and not an editor, then we raise HTTPForbidden.

In the same file, now edit the add_page view function:

61@view_config(route_name='add_page', renderer='tutorial:templates/edit.jinja2')
62def add_page(request):
63    user = request.identity
64    if user is None or user.role not in ('editor', 'basic'):
65        raise HTTPForbidden
66    pagename = request.matchdict['pagename']
67    if request.dbsession.query(models.Page).filter_by(name=pagename).count() > 0:
68        next_url = request.route_url('edit_page', pagename=pagename)
69        return HTTPSeeOther(location=next_url)
70    if request.method == 'POST':
71        body = request.params['body']
72        page = models.Page(name=pagename, data=body)
73        page.creator = request.identity
74        request.dbsession.add(page)
75        next_url = request.route_url('view_page', pagename=pagename)
76        return HTTPSeeOther(location=next_url)
77    save_url = request.route_url('add_page', pagename=pagename)
78    return dict(pagename=pagename, pagedata='', save_url=save_url)

Only the highlighted lines need to be changed.

If the user either is not logged in or is not in the basic or editor roles, then we raise HTTPForbidden, which will trigger our forbidden view to compute a response. However, we will hook this later to redirect to the login page. Also, now that we have request.identity, we no longer have to hard-code the creator as the editor user, so we can finally drop that hack.

These simple checks should protect our views.

Login, logout

Now that we've got the ability to detect logged-in users, we need to add the /login and /logout views so that they can actually login and logout!

Add routes for /login and /logout

Go back to tutorial/routes.py and add these two routes as highlighted:

3    config.add_route('view_wiki', '/')
4    config.add_route('login', '/login')
5    config.add_route('logout', '/logout')
6    config.add_route('view_page', '/{pagename}')

Note

The preceding lines must be added before the following view_page route definition:

6    config.add_route('view_page', '/{pagename}')

This is because view_page's route definition uses a catch-all "replacement marker" /{pagename} (see Route Pattern Syntax), which will catch any route that was not already caught by any route registered before it. Hence, for login and logout views to have the opportunity of being matched (or "caught"), they must be above /{pagename}.

Add login, logout, and forbidden views

Create a new file tutorial/views/auth.py, and add the following code to it:

 1from pyramid.csrf import new_csrf_token
 2from pyramid.httpexceptions import HTTPSeeOther
 3from pyramid.security import (
 4    remember,
 5    forget,
 6)
 7from pyramid.view import (
 8    forbidden_view_config,
 9    view_config,
10)
11
12from .. import models
13
14
15@view_config(route_name='login', renderer='tutorial:templates/login.jinja2')
16def login(request):
17    next_url = request.params.get('next', request.referrer)
18    if not next_url:
19        next_url = request.route_url('view_wiki')
20    message = ''
21    login = ''
22    if request.method == 'POST':
23        login = request.params['login']
24        password = request.params['password']
25        user = (
26            request.dbsession.query(models.User)
27            .filter_by(name=login)
28            .first()
29        )
30        if user is not None and user.check_password(password):
31            new_csrf_token(request)
32            headers = remember(request, user.id)
33            return HTTPSeeOther(location=next_url, headers=headers)
34        message = 'Failed login'
35        request.response.status = 400
36
37    return dict(
38        message=message,
39        url=request.route_url('login'),
40        next_url=next_url,
41        login=login,
42    )
43
44@view_config(route_name='logout')
45def logout(request):
46    next_url = request.route_url('view_wiki')
47    if request.method == 'POST':
48        new_csrf_token(request)
49        headers = forget(request)
50        return HTTPSeeOther(location=next_url, headers=headers)
51
52    return HTTPSeeOther(location=next_url)
53
54@forbidden_view_config(renderer='tutorial:templates/403.jinja2')
55def forbidden_view(exc, request):
56    if not request.is_authenticated:
57        next_url = request.route_url('login', _query={'next': request.url})
58        return HTTPSeeOther(location=next_url)
59
60    request.response.status = 403
61    return {}

This code adds three new views to the application:

  • The login view renders a login form and processes the post from the login form, checking credentials against our users table in the database.

    The check is done by first finding a User record in the database, then using our user.check_password method to compare the hashed passwords.

    At a privilege boundary we are sure to reset the CSRF token using pyramid.csrf.new_csrf_token(). If we were using sessions we would want to invalidate that as well.

    If the credentials are valid, then we use our authentication policy to store the user's id in the response using pyramid.security.remember().

    Finally, the user is redirected back to either the page which they were trying to access (next) or the front page as a fallback. This parameter is used by our forbidden view, as explained below, to finish the login workflow.

  • The logout view handles requests to /logout by clearing the credentials using pyramid.security.forget(), then redirecting them to the front page.

    At a privilege boundary we are sure to reset the CSRF token using pyramid.csrf.new_csrf_token(). If we were using sessions we would want to invalidate that as well.

  • The forbidden_view is registered using the pyramid.view.forbidden_view_config decorator. This is a special exception view, which is invoked when a pyramid.httpexceptions.HTTPForbidden exception is raised.

    By default, the view will return a "403 Forbidden" response and display our 403.jinja2 template (added below).

    However, if the user is not logged in, this view will handle a forbidden error by redirecting the user to /login. As a convenience, it also sets the next= query string to the current URL (the one that is forbidding access). This way, if the user successfully logs in, they will be sent back to the page which they had been trying to access.

Add the login.jinja2 template

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

{% extends 'layout.jinja2' %}

{% block title %}Login - {% endblock title %}

{% block content %}
<p>
<strong>
    Login
</strong><br>
{{ message }}
</p>
<form action="{{ url }}" method="post">
<input type="hidden" name="csrf_token" value="{{ get_csrf_token() }}">
<input type="hidden" name="next" value="{{ next_url }}">
<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">
</div>
<div class="form-group">
    <button type="submit" class="btn btn-default">Log In</button>
</div>
</form>
{% endblock content %}

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

Add the 403.jinja2 template

Create tutorial/templates/403.jinja2 with the following content:

{% extends "layout.jinja2" %}

{% block content %}
<h1><span class="font-semi-bold">Pyramid</span> <span class="smaller">Starter project</span></h1>
<p class="lead"><span class="font-semi-bold">403</span> Forbidden</p>
{% endblock content %}

The above template is referenced in the forbidden view that we just added in tutorial/views/auth.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 object. 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, or username basic and password basic, 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 object.

  • http://localhost:6543/FrontPage/edit_page invokes the edit_page view for the FrontPage page object. It is executable by only the editor user. If a different user invokes it, then the "403 Forbidden" page will be displayed. If an anonymous user invokes it, then a login form will be displayed.

  • http://localhost:6543/add_page/SomePageName invokes the add_page view for a page. If the page already exists, then it redirects the user to the edit_page view for the page object. It is executable by either the editor or basic user. If an anonymous user invokes it, then a login form will be displayed.

  • http://localhost:6543/SomePageName/edit_page invokes the edit_page view for an existing page, or generates an error if the page does not exist. It is editable by the basic user if the page was created by that user in the previous step. If instead the page was created by the editor user, then the login page should be shown for the basic user.