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 an authentication policy and a request.user computed property (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 denied access to any of the views that require permission, instead of a default "403 Forbidden" page (views/auth.py).

Authenticating requests

The core of Pyramid authentication is an authentication 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 authentication policy

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

 1from pyramid.authentication import AuthTktAuthenticationPolicy
 2from pyramid.authorization import ACLAuthorizationPolicy
 3
 4from .models import User
 5
 6
 7class MyAuthenticationPolicy(AuthTktAuthenticationPolicy):
 8    def authenticated_userid(self, request):
 9        user = request.user
10        if user is not None:
11            return user.id
12
13def get_user(request):
14    user_id = request.unauthenticated_userid
15    if user_id is not None:
16        user = request.dbsession.query(User).get(user_id)
17        return user
18
19def includeme(config):
20    settings = config.get_settings()
21    authn_policy = MyAuthenticationPolicy(
22        settings['auth.secret'],
23        hashalg='sha512',
24    )
25    config.set_authentication_policy(authn_policy)
26    config.set_authorization_policy(ACLAuthorizationPolicy())
27    config.add_request_method(get_user, 'user', reify=True)

Here we've defined:

  • A new authentication policy named MyAuthenticationPolicy, which is subclassed from Pyramid's pyramid.authentication.AuthTktAuthenticationPolicy, which tracks the userid using a signed cookie (lines 7-11).

  • A get_user function, which can convert the unauthenticated_userid from the policy into a User object from our database (lines 13-17).

  • The get_user is registered on the request as request.user to be used throughout our application as the authenticated User object for the logged-in user (line 27).

The logic in this file is a little bit interesting, so we'll go into detail about what's happening here:

First, the default authentication policies all provide a method named unauthenticated_userid which is responsible for the low-level parsing of the information in the request (cookies, headers, etc.). If a userid is found, then it is returned from this method. This is named unauthenticated_userid because, at the lowest level, it knows the value of the userid in the cookie, but it doesn't know if it's actually a user in our system (remember, anything the user sends to our app is untrusted).

Second, our application should only care about authenticated_userid and request.user, which have gone through our application-specific process of validating that the user is logged in.

In order to provide an authenticated_userid we need a verification step. That can happen anywhere, so we've elected to do it inside of the cached request.user computed property. This is a convenience that makes request.user the source of truth in our system. It is either None or a User object from our database. This is why the get_user function uses the unauthenticated_userid to check the database.

Configure the app

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
 2
 3
 4def main(global_config, **settings):
 5    """ This function returns a Pyramid WSGI application.
 6    """
 7    with Configurator(settings=settings) as config:
 8        config.include('pyramid_jinja2')
 9        config.include('.models')
10        config.include('.routes')
11        config.include('.security')
12        config.scan()
13    return config.make_wsgi_app()

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 for production, so open production.ini and add a different secret:

17retry.attempts = 3
18
19auth.secret = real-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:

5from pyramid.httpexceptions import (
6    HTTPForbidden,
7    HTTPFound,
8    HTTPNotFound,
9    )

Change the highlighted line.

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

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

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:

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

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 return a "403 Forbidden" response to the user. However, we will hook this later to redirect to the login page. Also, now that we have request.user, 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.httpexceptions import HTTPFound
 2from pyramid.security import (
 3    remember,
 4    forget,
 5    )
 6from pyramid.view import (
 7    forbidden_view_config,
 8    view_config,
 9)
10
11from ..models import User
12
13
14@view_config(route_name='login', renderer='../templates/login.jinja2')
15def login(request):
16    next_url = request.params.get('next', request.referrer)
17    if not next_url:
18        next_url = request.route_url('view_wiki')
19    message = ''
20    login = ''
21    if 'form.submitted' in request.params:
22        login = request.params['login']
23        password = request.params['password']
24        user = request.dbsession.query(User).filter_by(name=login).first()
25        if user is not None and user.check_password(password):
26            headers = remember(request, user.id)
27            return HTTPFound(location=next_url, headers=headers)
28        message = 'Failed login'
29
30    return dict(
31        message=message,
32        url=request.route_url('login'),
33        next_url=next_url,
34        login=login,
35        )
36
37@view_config(route_name='logout')
38def logout(request):
39    headers = forget(request)
40    next_url = request.route_url('view_wiki')
41    return HTTPFound(location=next_url, headers=headers)
42
43@forbidden_view_config()
44def forbidden_view(request):
45    next_url = request.route_url('login', _query={'next': request.url})
46    return HTTPFound(location=next_url)

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.

    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.

  • 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.

    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="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" name="form.submitted" value="Log In" 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.

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/FrontPage invokes the view_page view of the FrontPage page object. 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.

  • 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 (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_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 a different user (or the anonymous user) invokes it, then a login form will be displayed. Supplying the credentials with either the username editor and password editor, or username basic and password basic, will display the edit page form.

  • 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.

  • After logging in (as a result of hitting an edit or add page and submitting the login form with the editor credentials), we'll see a "Logout" link in the upper right hand corner. When we click it, we're logged out, redirected back to the front page, and a "Login" link is shown in the upper right hand corner.