Koen Deforche <koen@emweb.be>

For Wt 4.0.0 (September 19, 2017)

1. Prerequisites

In this tutorial, we use an example as a hands-on introduction to the Wt authentication module. This example is included in the Wt distribution, in examples/feature/auth1.

This introduction assumes that you have a reasonable understanding of Wt itself, in particular its stateful session model and the widget concept. If you haven’t done so yet, you may want to go through the Wt tutorial first.

2. Introduction

The authentication module implements the logic and widgets involved in getting users registered on your application, and letting them sign in. Note that this module is entirely optional, and simply implemented on top of Wt.

The module implements authentication. Its main purpose is to securely authenticate a user to sign in to your application. From your application, you will interact with the authentication module using a Wt::Auth::Login object, which you typically hold in your application object. It indicates the user currently signed in (if any), and propagates authentication events.

How you use this information for authorization or to customize the user experience is out of the scope of the module. Because of Wt’s built-in security features, with strong session hijacking mitigation, this is as straight forward as one can conceive it.

Currently, the module provides the following features, which can be separately enabled, configured or customized:

  • Password authentication, using best practices including salted hashing with strong cryptographic hash functions (such as bcrypt) and password strength checking.

  • Remember-me functionality, again using best practices, by associating authentication tokens stored in cookies to a user.

  • Verified email addresses using the typical confirmation email process.

  • Lost password functionality that uses the verified email address to prompt a user to enter a new password.

  • Authentication using 3rd party Identity Providers, currently using OAuth 2, with support for multiple identities per user. Currently, only Google and Facebook are supported for authentication, but Wt may support other OAuth 2 providers, like the standardized OpenIDConnect, in the future.

  • Registration logic, which includes also the logic needed to merge new (federated login) identities into existing user profiles. For example, if a user previously registered using a user name and password, he may later also authenticate using for example his Google Account and this new identity is added to his existing account.

The logic for these features is implemented separately from the user interface components, which can be customized or completely replaced with your own widgets.

Next to traditional password-based authentication, we’ve been careful to have a design that accommodates 3rd party identity providers (federated login) such as Google, Twitter, Facebook, etc… and other authentication mechanisms in general (authenticating reverse proxies, client SSL certificates, LDAP, token devices …).

Obviously, the authentication logic needs to talk to a storage system, and it is designed to hook into a storage system using an abstract interface. A default implementation that leverages Wt::Dbo, Wt’s ORM, is provided.

3. Module organization

The following picture illustrates the main classes of the module.

img/auth.png

It uses a classical separation between Model classes and View classes (which are the widgets).

There are three types of model classes:

  • Service classes are designed to be shared across all sessions (they do not have any state besides configuration). They contain logic which does not require transient state in a session.

  • Session bound model classes are usually kept in a session for the entire lifetime of a session (but don’t need to be).

  • Transient model classes play an active role in the user-interface, and are instantiated in the context of certain view components. They implement logic which involves state while the user is progressing through the login and registration process.

4. Example

We’ll walk through a small example which is a basic application that uses the authentication module (included in the Wt distribution in examples/feature/auth1). It is about 200 lines of C++ (which we’ll discuss below), and has the following features:

  • Password-based authentication and registration

  • OAuth-2 login and registration, for Google and Facebook accounts

  • Password attempt throttling

  • Email verification and a lost password procedure

  • Remember-me tokens

  • And by virtue of Wt itself, falls back to plain HTML behavior if the browser does not support Ajax, strong security, spam resilience, etc…

This example should help you to understand how to add authentication support to a new or existing Wt project.

4.1. Setting up a user database

We will be using the default implementation for an authentication database using Wt::Dbo, with the default persistence classes for authentication. This database implementation is found in Wt::Auth::Dbo::UserDatabase, and it uses Wt::Auth::Dbo::AuthInfo as the persistence class for authentication information, which itself references two other persistence classes:

  • A user’s "identities" are stored in a separate table. An identity uniquely identifies a user. Traditionally, a user would have only a single identity which is his login name (which could be his email address). But a user may accumulate more identities, corresponding to accounts with 3rd party identity providers. By allowing multiple identities, the user may identify using a choice of methods.

  • Authentication tokens are stored in a separate table. An authentication token usually corresponds to a "remember-me" cookie, and a user may have multiple "remember-me" cookies when using different computers.

In addition, we define a User type to which we can add the application data for a particular user (this could be address information, birth date, preferences, user role, etc…), and which we want to link up with the authentication system.

The definition and persistence mapping for (a currently empty) User type is as given below:

User.h
#include <Wt/Dbo/Types.h>
#include <Wt/WGlobal.h>

namespace dbo = Wt::Dbo;

class User;
using AuthInfo = Wt::Auth::Dbo::AuthInfo<User>;

class User {
public:
  template<class Action>
  void persist(Action& a)
  {
  }
};

DBO_EXTERN_TEMPLATES(User)

We declare a type alias for AuthInfo, which links the authentication information persistence class to our custom User information persistence class.

Next, we define a session class, which encapsulates the connection to the database to store authentication information, and which also tracks the user currently logged in, in a web session. We choose to use the Wt::Dbo::Session class as a base class (which could just as well be an embedded member).

Later on, we’ll see how each web session will instantiate its own persistence/authentication Session object.

Session.h
#include <Wt/Auth/Login.h>
#include <Wt/Auth/UserDatabase.h>

#include <Wt/Dbo/Session.h>
#include <Wt/Dbo/ptr.h>

#include "User.h"

namespace dbo = Wt::Dbo;

using UserDatabase = Wt::Auth::Dbo::UserDatabase<AuthInfo>;

class Session : public dbo::Session
{
public:
  Session(const std::string& sqliteDb);

  Wt::Auth::AbstractUserDatabase& users();
  Wt::Auth::Login& login() { return login_; }

  ...

private:
  std::unique_ptr<UserDatabase> users_;
  Wt::Auth::Login login_;

  ...
};

Notice the type alias for UserDatabase, which states that we will be using the Wt::Auth::Dbo::UserDatabase implementation using AuthInfo, for which we declared a type alias earlier on. You are of course free to provide another implementation for Wt::Auth::AbstractUserDatabase which is not based on Wt::Dbo.

We also embed a Wt::Auth::Login member here, which is a small model class that holds the current login information. The login/logout widgets will manipulate this login object, while the rest of our application will listen to login changes from this object to adapt to the user currently logged in.

The Session constructor sets up the database session.

Session.C (constructor)
#include "Session.h"
#include "User.h"

#include "Wt/Auth/Dbo/AuthInfo.h"

#include "Wt/Dbo/backend/Sqlite3.h"

using namespace Wt;

Session::Session(const std::string& sqliteDb)
{
  auto connection = std::make_unique<Dbo::backend::Sqlite3>(sqliteDb);
  setConnection(std::move(connection_));

  mapClass<User>("user");
  mapClass<AuthInfo>("auth_info");
  mapClass<AuthInfo::AuthIdentityType>("auth_identity");
  mapClass<AuthInfo::AuthTokenType>("auth_token");

  try {
    createTables();
    std::cerr << "Created database." << std::endl;
  } catch (Wt::Dbo::Exception& e) {
    std::cerr << e.what() << std::endl;
    std::cerr << "Using existing database";
  }

  users_ = std::make_unique<UserDatabase>(*this);
}

The example uses a SQLite3 database (a cuddly database convenient for development), and we map four persistence classes to tables.

We then create the data schema if needed, which will automatically issue the following SQL:

create table "user" (
  "id" integer primary key autoincrement,
  "version" integer not null
)

create table "auth_info" (
  "id" integer primary key autoincrement,
  "version" integer not null,
  "user_id" bigint,
  "password_hash" varchar(100) not null,
  "password_method" varchar(20) not null,
  "password_salt" varchar(20) not null,
  "status" integer not null,
  "failed_login_attempts" integer not null,
  "last_login_attempt" text,
  "email" varchar(256) not null,
  "unverified_email" varchar(256) not null,
  "email_token" varchar(64) not null,
  "email_token_expires" text,
  "email_token_role" integer not null,
  constraint "fk_auth_info_user" foreign key
   ("user_id") references "user" ("id")
   on delete cascade deferrable initially deferred
)

create table "auth_token" (
  "id" integer primary key autoincrement,
  "version" integer not null,
  "auth_info_id" bigint,
  "value" varchar(64) not null,
  "expires" text,
  constraint "fk_auth_token_auth_info" foreign key
   ("auth_info_id") references "auth_info" ("id")
   on delete cascade deferrable initially deferred
)

create table "auth_identity" (
  "id" integer primary key autoincrement,
  "version" integer not null,
  "auth_info_id" bigint,
  "provider" varchar(64) not null,
  "identity" varchar(512) not null,
  constraint "fk_auth_identity_auth_info" foreign key
   ("auth_info_id") references "auth_info" ("id")
   on delete cascade defferable initially deferred
)

Notice the auth_info, auth_token and auth_identity tables that define the storage for our authentication system.

4.2. Configuring authentication

The service classes (Wt::Auth::AuthService, Wt::Auth::PasswordService, and Wt::Auth::OAuthService), can be shared between sessions and contain the configuration and logic which does not require transient session state.

A good location to add these service classes are inside a specialized Wt::WServer instance, of which you usually also have only one in a Wt process. You could also create a singleton for them. To keep the example simple, we will declare them simply as global variables (but within file scope): myAuthService, myPasswordService, and myOAuth.

Session.C (authentication services)
#include "Wt/Auth/AuthService.h"
#include "Wt/Auth/HashFunction.h"
#include "Wt/Auth/PasswordService.h"
#include "Wt/Auth/PasswordStrengthValidator.h"
#include "Wt/Auth/PasswordVerifier.h"
#include "Wt/Auth/GoogleService.h"
#include "Wt/Auth/FacebookService.h"

namespace {
  Wt::Auth::AuthService myAuthService;
  Wt::Auth::PasswordService myPasswordService{myAuthService};
  std::vector<std::unique_ptr<Wt::Auth::OAuthService>> myOAuth;
}

void Session::configureAuth()
{
  myAuthService.setAuthTokensEnabled(true, "logincookie");
  myAuthService.setEmailVerificationEnabled(true);
  myAuthService.setEmailVerificationRequired(true);

  std::unique_ptr<Wt::Auth::PasswordVerifier> verifier =
    std::make_unique<Wt::Auth::PasswordVerifier>();
  verifier->addHashFunction(std::make_unique<Wt::Auth::BCryptHashFunction>(7));
  myPasswordService.setVerifier(std::move(verifier));
  myPasswordService.setAttemptThrottlingEnabled(true);
  myPasswordService.setStrengthValidator(std::make_unique<Wt::Auth::PasswordStrengthValidator>());

  if (Wt::Auth::GoogleService::configured())
    myOAuthServices.push_back(std::make_unique<Wt::Auth::GoogleService>(myAuthService));

  if (Wt::Auth::FacebookService::configured())
    myOAuthServices.push_back(std::make_unique<Wt::Auth::FacebookService>(myAuthService));

  for (unsigned i = 0; i < myOAuthServices.size(); ++i)
    myOAuthServices[i]->generateRedirectEndpoint();
}

Wt::Auth::AbstractUserDatabase& Session::users()
{
  return *users_;
}

const Wt::Auth::AuthService& Session::auth()
{
  return myAuthService;
}

const Wt::Auth::PasswordService& Session::passwordAuth()
{
  return myPasswordService;
}

const std::vector<const Wt::Auth::OAuthService *>& Session::oAuth()
{
  std::vector<const Wt::Auth::OAuthService *> result;
  for (auto &auth : myOAuthServices) {
    result.push_back(auth.get());
  }
  return result;
}

The Wt::Auth::AuthService is configured to support "remember-me" functionality, and email verification.

The Wt::Auth::PasswordService needs a hash function to safely store passwords. You can actually define more than one hash function, which is useful only if you want to migrate to a new hash function while still supporting existing passwords. When a user logs in, and he is not using the "preferred" hash function, his password will be rehashed with the preferred one. In this example, we will use bcrypt which is included as a hash function in Wt::Auth.

We also enable password attempt throttling: this mitigates brute force password guessing attempts.

Finally, we also use two (but later, perhaps more) Wt::Auth::OAuthService classes. You need one service per identity provider. In this case, we add Google and Facebook as identity providers.

4.3. The user interface

We create a specialized Wt::WApplication which contains our authentication session, and instantiates a Wt::Auth::AuthWidget. This widget shows a login or logout form (depending on the login status), and also hooks into default forms for registration, lost passwords, and handling of email-sent tokens in URLs).

User interface
#include <Wt/WApplication.h>
#include <Wt/WBootstrapTheme.h>
#include <Wt/WContainerWidget.h>
#include <Wt/WServer.h>

#include <Wt/Auth/AuthWidget.h>
#include <Wt/Auth/PasswordService.h>

#include "model/Session.h"

class AuthApplication : public Wt::WApplication
{
public:
  AuthApplication(const Wt::WEnvironment& env)
    : Wt::WApplication(env),
      session_(appRoot() + "auth.db")
  {
    session_.login().changed().connect(this, &AuthApplication::authEvent);

    root()->addStyleClass("container");
    setTheme(std::make_shared<Wt::WBootstrapTheme>());

    useStyleSheet("css/style.css");

    std::unique_ptr<Wt::Auth::AuthWidget> authWidget =
      std::make_unique<Wt::Auth::AuthWidget>(Session::auth(), session_.users(), session_.login());

    authWidget->model()->addPasswordAuth(&Session::passwordAuth());
    authWidget->model()->addOAuth(Session::oAuth());
    authWidget->setRegistrationEnabled(true);

    authWidget->processEnvironment();

    root()->addWidget(std::move(authWidget));
  }

  void authEvent() {
    if (session_.login().loggedIn()) {
      const Wt::Auth::User& u = session_.login().user();
      log("notice")
        << "User " << u.id()
        << " (" << u.identity(Wt::Auth::Identity::LoginName) << ")"
        << " logged in.";
    } else
      log("notice") << "User logged out.";
  }

private:
  Session session_;
};

The last part is our main function where we setup the application server:

Application server setup
std::unique_ptr<Wt::WApplication> createApplication(const Wt::WEnvironment &env)
{
  return std::make_unique<AuthApplication>(env);
}

int main(int argc, char **argv)
{
  try {
    Wt::WServer server{argc, argv, WTHTTP_CONFIGURATION};

    server.addEntryPoint(Wt::EntryPointType::Application, createApplication);

    Session::configureAuth();

    server.run();
  } catch (Wt::WServer::Exception& e) {
    std::cerr << e.what() << std::endl;
  } catch (Wt::Dbo::Exception &e) {
    std::cerr << "Dbo exception: " << e.what() << std::endl;
  } catch (std::exception &e) {
    std::cerr << "exception: " << e.what() << std::endl;
  }
}