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:
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:
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();
});
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:
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>
<div class="float-right">
<a class="btn btn-outline-danger" href="/logout" role="button" aria-pressed="true">Logout (${username})</a>
</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.
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:
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));"
);
/*
* root / admin
* foo / bar
* 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:
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(),