Access control and authentication
Vert.x provides a wide range of options for doing authentication and authorization. The officially supported modules cover JDBC, MongoDB, Apache Shiro, htdigest
files, OAuth2 with well-known providers and JWT (JSON web tokens).
While the next section will cover JWT, this one focuses on using JDBC-based authentication, reusing the wiki database.
The goal is to require users to authenticate for using the wiki, and have role-based permissions:
having no role only allows reading pages,
having a writer role allows editing pages,
having an editor role allows creating, editing and deleting pages,
having an admin role is equivalent to having all possible roles.
Refactoring the JDBC configuration
In the previous steps, only the database verticle and service where aware of the JDBC configuration. Now the HTTP service vertice also needs to share the same JDBC access.
To do that we extract configuration parameters and default values to an interface:
package io.vertx.guides.wiki;
public interface DatabaseConstants {
String CONFIG_WIKIDB_JDBC_URL = "wikidb.jdbc.url";
String CONFIG_WIKIDB_JDBC_DRIVER_CLASS = "wikidb.jdbc.driver_class";
String CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE = "wikidb.jdbc.max_pool_size";
String DEFAULT_WIKIDB_JDBC_URL = "jdbc:hsqldb:file:db/wiki";
String DEFAULT_WIKIDB_JDBC_DRIVER_CLASS = "org.hsqldb.jdbcDriver";
int DEFAULT_JDBC_MAX_POOL_SIZE = 30;
}
Now in WikiDatabaseVerticle
we use these constants as follows:
JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
.put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
.put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
.put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, DEFAULT_JDBC_MAX_POOL_SIZE)));
Adding JDBC authentication to routes
The first step is to add the vertx-auth-jdbc
module to the Maven dependencies list:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-auth-jdbc</artifactId>
</dependency>
Back to the HttpServerVerticle
class code, we create an authentication provider:
JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
.put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
.put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
.put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, DEFAULT_JDBC_MAX_POOL_SIZE)));
JDBCAuth auth = JDBCAuth.create(vertx, dbClient);
The JDBCAuth
object instance is then used to deal with server-side user sessions:
Router router = Router.router(vertx);
router.route().handler(CookieHandler.create());
router.route().handler(BodyHandler.create());
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
router.route().handler(UserSessionHandler.create(auth)); (1)
AuthHandler authHandler = RedirectAuthHandler.create(auth, "/login"); (2)
router.route("/").handler(authHandler); (3)
router.route("/wiki/*").handler(authHandler);
router.route("/action/*").handler(authHandler);
router.get("/").handler(this::indexHandler);
router.get("/wiki/:page").handler(this::pageRenderingHandler);
router.post("/action/save").handler(this::pageUpdateHandler);
router.post("/action/create").handler(this::pageCreateHandler);
router.get("/action/backup").handler(this::backupHandler);
router.post("/action/delete").handler(this::pageDeletionHandler);
We install a user session handler for all routes.
This automatically redirects requests to
/login
when there is no user session for the request.We install
authHandler
for all routes where authentication is required.
Finally, we need to create 3 routes for displaying a login form, handling login form submissions and logging out users:
router.get("/login").handler(this::loginHandler);
router.post("/login-auth").handler(FormLoginHandler.create(auth)); (1)
router.get("/logout").handler(context -> {
context.clearUser(); (2)
context.response()
.setStatusCode(302)
.putHeader("Location", "/")
.end();
});
FormLoginHandler
is a helper for processing login submission requests. By default it expects the HTTP POST request to have:username
as the login,password
as the password, andreturn_url
as the URL to redirect to upon success.Logging out a user is a simple as clearing it from the current
RoutingContext
.
The code for the loginHandler
method is:
private void loginHandler(RoutingContext context) {
context.put("title", "Login");
templateEngine.render(context.data(), "templates/login.ftl", ar -> {
if (ar.succeeded()) {
context.response().putHeader("Content-Type", "text/html");
context.response().end(ar.result());
} else {
context.fail(ar.cause());
}
});
}
The HTML template is placed in src/main/resources/templates/login.ftl
:
<#include "header.ftl">
<div class="row">
<div class="col-md-12 mt-1">
<form action="/login-auth" method="POST">
<div class="form-group">
<input type="text" name="username" placeholder="login">
<input type="password" name="password" placeholder="password">
<input type="hidden" name="return_url" value="/">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
<#include "footer.ftl">
The login page looks as follows:
Supporting features based on roles
Features need to be activated only if the user has sufficient permissions. In the following screenshot an administrator can create a page and perform a backup:
By contrast a user with no role cannot perform these actions:
To do that, we can access the RoutingContext
user reference, and query for permissions. Here is how this is implemented for the indexHandler
handler method:
private void indexHandler(RoutingContext context) {
context.user().isAuthorized("create", res -> { (1)
boolean canCreatePage = res.succeeded() && res.result(); (2)
dbService.fetchAllPages(reply -> {
if (reply.succeeded()) {
context.put("title", "Wiki home");
context.put("pages", reply.result().getList());
context.put("canCreatePage", canCreatePage); (3)
context.put("username", context.user().principal().getString("username")); (4)
templateEngine.render(context.data(), "templates/index.ftl", ar -> {
if (ar.succeeded()) {
context.response().putHeader("Content-Type", "text/html");
context.response().end(ar.result());
} else {
context.fail(ar.cause());
}
});
} else {
context.fail(reply.cause());
}
});
});
}
This is how a permission query is made. Note that this is an asynchronous operation.
We use the result to…
…leverage it in the HTML template.
We also have access to the user login.
The template code has been modified to only render certain fragments based on the value of canCreatePage
:
<#include "header.ftl">
<div class="row">
<div class="col-md-12 mt-1">
<#if canCreatePage>
<div class="float-right">
<form class="form-inline" action="/action/create" method="post">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="New page name">
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</#if>
<h1 class="display-4">${title}</h1>
<div class="float-right">
<a class="btn btn-outline-danger" href="/logout" role="button" aria-pressed="true">Logout (${username})</a>
</div>
</div>
<div class="col-md-12 mt-1">
<#list pages>
<h2>Pages:</h2>
<ul>
<#items as page>
<li><a href="/wiki/${page}">${page}</a></li>
</#items>
</ul>
<#else>
<p>The wiki is currently empty!</p>
</#list>
<#if canCreatePage>
<#if backup_gist_url?has_content>
<div class="alert alert-success" role="alert">
Successfully created a backup:
<a href="${backup_gist_url}" class="alert-link">${backup_gist_url}</a>
</div>
<#else>
<p>
<a class="btn btn-outline-secondary btn-sm" href="/action/backup" role="button" aria-pressed="true">Backup</a>
</p>
</#if>
</#if>
</div>
</div>
<#include "footer.ftl">
The code is similar for ensuring that updating or deleting a page is restricted to certain roles and is available from the guide Git repository.
It is important to ensure that checks are also being done on HTTP POST request handlers and not just when rendering HTML pages. Indeed, malicious attackers could still craft requests and perform actions while not being authenticated. Here is how to protect page deletions by wrapping the pageDeletionHandler
code inside a topmost permission check:
private void pageDeletionHandler(RoutingContext context) {
context.user().isAuthorized("delete", res -> {
if (res.succeeded() && res.result()) {
// Original code:
dbService.deletePage(Integer.valueOf(context.request().getParam("id")), reply -> {
if (reply.succeeded()) {
context.response().setStatusCode(303);
context.response().putHeader("Location", "/");
context.response().end();
} else {
context.fail(reply.cause());
}
});
} else {
context.response().setStatusCode(403).end();
}
});
}
Populating the database with user and role data
A last step is required for assembling all pieces of our authentication puzzle. We leave adding user registration and management as an exercice left to the reader, and instead we add some code to ensure that the database is being populated with some roles and accounts:
Login | Password | Roles |
---|---|---|
root | admin | admin (create, delete, update) |
foo | bar | editor (create, delete, update), writer (update) |
bar | baz | writer (update) |
baz | baz | / |
The vertx-auth-jdbc
prescribes a default database schema with 3 tables: 1 for users (with salted passwords), 1 for role permissions, and 1 to map users to roles. That schema can be changed and configured, but in many cases sticking to the default is a very good option.
To do that, we are going to deploy a verticle whose sole role is performing the initialisation work:
package io.vertx.guides.wiki.http;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import static io.vertx.guides.wiki.DatabaseConstants.*;
public class AuthInitializerVerticle extends AbstractVerticle {
private final Logger logger = LoggerFactory.getLogger(AuthInitializerVerticle.class);
@Override
public void start() throws Exception {
List<String> schemaCreation = Arrays.asList(
"create table if not exists user (username varchar(255), password varchar(255), password_salt varchar(255));",
"create table if not exists user_roles (username varchar(255), role varchar(255));",
"create table if not exists roles_perms (role varchar(255), perm varchar(255));"
);
/*
* Passwords:
* root / admin
* foo / bar
* bar / baz
* baz / baz
*/
List<String> dataInit = Arrays.asList( (1)
"insert into user values ('root', 'C705F9EAD3406D0C17DDA3668A365D8991E6D1050C9A41329D9C67FC39E53437A39E83A9586E18C49AD10E41CBB71F0C06626741758E16F9B6C2BA4BEE74017E', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
"insert into user values ('foo', 'C3F0D72C1C3C8A11525B4563BAFF0E0F169114DE36796A595B78A373C522C0FF81BC2A683E2CB882A077847E8FD4DA09F1993072A4E9D7671313E4E5DB898F4E', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
"insert into user values ('bar', 'AEDD3E9FFCB847596A0596306A4303CC61C43D9904A0184951057D07D2FE2F36FA855C58EBCA9F3AEC9C65C46656F393E3D0F8711881F250D0D860F143A7A281', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
"insert into user values ('baz', 'AEDD3E9FFCB847596A0596306A4303CC61C43D9904A0184951057D07D2FE2F36FA855C58EBCA9F3AEC9C65C46656F393E3D0F8711881F250D0D860F143A7A281', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
"insert into roles_perms values ('editor', 'create');",
"insert into roles_perms values ('editor', 'delete');",
"insert into roles_perms values ('editor', 'update');",
"insert into roles_perms values ('writer', 'update');",
"insert into roles_perms values ('admin', 'create');",
"insert into roles_perms values ('admin', 'delete');",
"insert into roles_perms values ('admin', 'update');",
"insert into user_roles values ('root', 'admin');",
"insert into user_roles values ('foo', 'editor');",
"insert into user_roles values ('foo', 'writer');",
"insert into user_roles values ('bar', 'writer');"
);
JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
.put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
.put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
.put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, DEFAULT_JDBC_MAX_POOL_SIZE)));
dbClient.getConnection(car -> {
if (car.succeeded()) {
SQLConnection connection = car.result();
connection.batch(schemaCreation, ar -> schemaCreationHandler(dataInit, connection, ar));
} else {
logger.error("Cannot obtain a database connection", car.cause());
}
});
}
private void schemaCreationHandler(List<String> dataInit, SQLConnection connection, AsyncResult<List<Integer>> ar) {
if (ar.succeeded()) {
connection.query("select count(*) from user;", testQueryHandler(dataInit, connection));
} else {
connection.close();
logger.error("Schema creation failed", ar.cause());
}
}
private Handler<AsyncResult<ResultSet>> testQueryHandler(List<String> dataInit, SQLConnection connection) {
return ar -> {
if (ar.succeeded()) {
if (ar.result().getResults().get(0).getInteger(0) == 0) {
logger.info("Need to insert data");
connection.batch(dataInit, batchInsertHandler(connection));
} else {
logger.info("No need to insert data");
connection.close();
}
} else {
connection.close();
logger.error("Could not check the number of users in the database", ar.cause());
}
};
}
private Handler<AsyncResult<List<Integer>>> batchInsertHandler(SQLConnection connection) {
return ar -> {
if (ar.succeeded()) {
logger.info("Successfully inserted data");
} else {
logger.error("Could not insert data", ar.cause());
}
connection.close();
};
}
}
- The hashed values can be generated using
auth.computeHash(password, salt)
whereauth
is aJDBCAuth
instance. Salt values can also be generated usingauth.generateSalt()
.
This impacts the MainVerticle
class, as we now deploy it first:
public class MainVerticle extends AbstractVerticle {
@Override
public void start(Promise<Void> promise) {
Promise<String> dbDeploymentPromise = Promise.promise();
vertx.deployVerticle(new WikiDatabaseVerticle(), dbDeploymentPromise);
Future<String> authDeploymentFuture = dbDeploymentPromise.future().compose(id -> {
Promise<String> deployPromise = Promise.promise();
vertx.deployVerticle(new AuthInitializerVerticle(), deployPromise);
return deployPromise.future();
});
authDeploymentFuture.compose(id -> {
Promise<String> deployPromise = Promise.promise();
vertx.deployVerticle("io.vertx.guides.wiki.http.HttpServerVerticle", new DeploymentOptions().setInstances(2), deployPromise);
return deployPromise.future();
});
authDeploymentFuture.setHandler(ar -> {
if (ar.succeeded()) {
promise.complete();
} else {
promise.fail(ar.cause());
}
});
}
}
Finally, we also need to update the ApiTest
class to setup the in-memory database for both the authentication and wiki storage:
JsonObject dbConf = new JsonObject()
.put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
.put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);
vertx.deployVerticle(new AuthInitializerVerticle(),
new DeploymentOptions().setConfig(dbConf), context.asyncAssertSuccess());
vertx.deployVerticle(new WikiDatabaseVerticle(),
new DeploymentOptions().setConfig(dbConf), context.asyncAssertSuccess());