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:

    1. JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
    2. .put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
    3. .put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
    4. .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:

    1. <dependency>
    2. <groupId>io.vertx</groupId>
    3. <artifactId>vertx-auth-jdbc</artifactId>
    4. </dependency>

    Back to the HttpServerVerticle class code, we create an authentication provider:

    1. JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
    2. .put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
    3. .put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
    4. .put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, DEFAULT_JDBC_MAX_POOL_SIZE)));
    5. JDBCAuth auth = JDBCAuth.create(vertx, dbClient);

    The JDBCAuth object instance is then used to deal with server-side user sessions:

    1. We install a user session handler for all routes.

    2. This automatically redirects requests to /login when there is no user session for the request.

    3. 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:

    1. router.get("/login").handler(this::loginHandler);
    2. router.post("/login-auth").handler(FormLoginHandler.create(auth)); (1)
    3. router.get("/logout").handler(context -> {
    4. context.clearUser(); (2)
    5. context.response()
    6. .setStatusCode(302)
    7. .putHeader("Location", "/")
    8. .end();
    9. });
    1. Logging out a user is a simple as clearing it from the current RoutingContext.

    The code for the loginHandler method is:

    1. private void loginHandler(RoutingContext context) {
    2. context.put("title", "Login");
    3. templateEngine.render(context.data(), "templates/login.ftl", ar -> {
    4. if (ar.succeeded()) {
    5. context.response().putHeader("Content-Type", "text/html");
    6. context.response().end(ar.result());
    7. } else {
    8. context.fail(ar.cause());
    9. }
    10. });
    11. }

    The HTML template is placed in src/main/resources/templates/login.ftl:

    1. <#include "header.ftl">
    2. <div class="row">
    3. <div class="col-md-12 mt-1">
    4. <form action="/login-auth" method="POST">
    5. <div class="form-group">
    6. <input type="text" name="username" placeholder="login">
    7. <input type="password" name="password" placeholder="password">
    8. <input type="hidden" name="return_url" value="/">
    9. <button type="submit" class="btn btn-primary">Login</button>
    10. </div>
    11. </form>
    12. </div>
    13. </div>
    14. <#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:

    as root

    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:

    1. This is how a permission query is made. Note that this is an asynchronous operation.

    2. We use the result to…​

    3. …​leverage it in the HTML template.

    4. 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:

    1. <#include "header.ftl">
    2. <div class="row">
    3. <div class="col-md-12 mt-1">
    4. <#if canCreatePage>
    5. <div class="float-right">
    6. <form class="form-inline" action="/action/create" method="post">
    7. <div class="form-group">
    8. <input type="text" class="form-control" id="name" name="name" placeholder="New page name">
    9. </div>
    10. <button type="submit" class="btn btn-primary">Create</button>
    11. </form>
    12. </div>
    13. </#if>
    14. <div class="float-right">
    15. <a class="btn btn-outline-danger" href="/logout" role="button" aria-pressed="true">Logout (${username})</a>
    16. </div>
    17. <div class="col-md-12 mt-1">
    18. <#list pages>
    19. <h2>Pages:</h2>
    20. <ul>
    21. <#items as page>
    22. <li><a href="/wiki/${page}">${page}</a></li>
    23. </#items>
    24. </ul>
    25. <#else>
    26. <p>The wiki is currently empty!</p>
    27. </#list>
    28. <#if canCreatePage>
    29. <#if backup_gist_url?has_content>
    30. <div class="alert alert-success" role="alert">
    31. Successfully created a backup:
    32. <a href="${backup_gist_url}" class="alert-link">${backup_gist_url}</a>
    33. </div>
    34. <#else>
    35. <p>
    36. <a class="btn btn-outline-secondary btn-sm" href="/action/backup" role="button" aria-pressed="true">Backup</a>
    37. </p>
    38. </#if>
    39. </#if>
    40. </div>
    41. </div>
    42. <#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.

    1. private void pageDeletionHandler(RoutingContext context) {
    2. context.user().isAuthorized("delete", res -> {
    3. if (res.succeeded() && res.result()) {
    4. // Original code:
    5. dbService.deletePage(Integer.valueOf(context.request().getParam("id")), reply -> {
    6. if (reply.succeeded()) {
    7. context.response().setStatusCode(303);
    8. context.response().putHeader("Location", "/");
    9. context.response().end();
    10. } else {
    11. context.fail(reply.cause());
    12. }
    13. });
    14. } else {
    15. context.response().setStatusCode(403).end();
    16. }
    17. });
    18. }

    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:

    1. package io.vertx.guides.wiki.http;
    2. import io.vertx.core.AbstractVerticle;
    3. import io.vertx.core.AsyncResult;
    4. import io.vertx.core.Handler;
    5. import io.vertx.core.json.JsonObject;
    6. import io.vertx.ext.jdbc.JDBCClient;
    7. import io.vertx.ext.sql.ResultSet;
    8. import io.vertx.ext.sql.SQLConnection;
    9. import org.slf4j.Logger;
    10. import org.slf4j.LoggerFactory;
    11. import java.util.Arrays;
    12. import java.util.List;
    13. import static io.vertx.guides.wiki.DatabaseConstants.*;
    14. public class AuthInitializerVerticle extends AbstractVerticle {
    15. private final Logger logger = LoggerFactory.getLogger(AuthInitializerVerticle.class);
    16. @Override
    17. public void start() throws Exception {
    18. List<String> schemaCreation = Arrays.asList(
    19. "create table if not exists user (username varchar(255), password varchar(255), password_salt varchar(255));",
    20. "create table if not exists user_roles (username varchar(255), role varchar(255));",
    21. "create table if not exists roles_perms (role varchar(255), perm varchar(255));"
    22. );
    23. /*
    24. * root / admin
    25. * foo / bar
    26. * baz / baz
    27. */
    28. List<String> dataInit = Arrays.asList( (1)
    29. "insert into user values ('root', 'C705F9EAD3406D0C17DDA3668A365D8991E6D1050C9A41329D9C67FC39E53437A39E83A9586E18C49AD10E41CBB71F0C06626741758E16F9B6C2BA4BEE74017E', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
    30. "insert into user values ('foo', 'C3F0D72C1C3C8A11525B4563BAFF0E0F169114DE36796A595B78A373C522C0FF81BC2A683E2CB882A077847E8FD4DA09F1993072A4E9D7671313E4E5DB898F4E', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
    31. "insert into user values ('bar', 'AEDD3E9FFCB847596A0596306A4303CC61C43D9904A0184951057D07D2FE2F36FA855C58EBCA9F3AEC9C65C46656F393E3D0F8711881F250D0D860F143A7A281', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
    32. "insert into user values ('baz', 'AEDD3E9FFCB847596A0596306A4303CC61C43D9904A0184951057D07D2FE2F36FA855C58EBCA9F3AEC9C65C46656F393E3D0F8711881F250D0D860F143A7A281', '017DC3D7F89CD5E873B16E6CCE9A2307C8E3D9C5758741EEE49A899FFBC379D8');",
    33. "insert into roles_perms values ('editor', 'create');",
    34. "insert into roles_perms values ('editor', 'delete');",
    35. "insert into roles_perms values ('editor', 'update');",
    36. "insert into roles_perms values ('writer', 'update');",
    37. "insert into roles_perms values ('admin', 'create');",
    38. "insert into roles_perms values ('admin', 'delete');",
    39. "insert into roles_perms values ('admin', 'update');",
    40. "insert into user_roles values ('root', 'admin');",
    41. "insert into user_roles values ('foo', 'editor');",
    42. "insert into user_roles values ('foo', 'writer');",
    43. "insert into user_roles values ('bar', 'writer');"
    44. );
    45. JDBCClient dbClient = JDBCClient.createShared(vertx, new JsonObject()
    46. .put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, DEFAULT_WIKIDB_JDBC_URL))
    47. .put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, DEFAULT_WIKIDB_JDBC_DRIVER_CLASS))
    48. .put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, DEFAULT_JDBC_MAX_POOL_SIZE)));
    49. dbClient.getConnection(car -> {
    50. if (car.succeeded()) {
    51. SQLConnection connection = car.result();
    52. connection.batch(schemaCreation, ar -> schemaCreationHandler(dataInit, connection, ar));
    53. } else {
    54. logger.error("Cannot obtain a database connection", car.cause());
    55. }
    56. });
    57. }
    58. private void schemaCreationHandler(List<String> dataInit, SQLConnection connection, AsyncResult<List<Integer>> ar) {
    59. if (ar.succeeded()) {
    60. connection.query("select count(*) from user;", testQueryHandler(dataInit, connection));
    61. } else {
    62. connection.close();
    63. logger.error("Schema creation failed", ar.cause());
    64. }
    65. }
    66. private Handler<AsyncResult<ResultSet>> testQueryHandler(List<String> dataInit, SQLConnection connection) {
    67. return ar -> {
    68. if (ar.succeeded()) {
    69. if (ar.result().getResults().get(0).getInteger(0) == 0) {
    70. logger.info("Need to insert data");
    71. connection.batch(dataInit, batchInsertHandler(connection));
    72. } else {
    73. logger.info("No need to insert data");
    74. connection.close();
    75. }
    76. } else {
    77. connection.close();
    78. logger.error("Could not check the number of users in the database", ar.cause());
    79. }
    80. };
    81. }
    82. private Handler<AsyncResult<List<Integer>>> batchInsertHandler(SQLConnection connection) {
    83. return ar -> {
    84. if (ar.succeeded()) {
    85. logger.info("Successfully inserted data");
    86. } else {
    87. logger.error("Could not insert data", ar.cause());
    88. }
    89. connection.close();
    90. };
    91. }
    92. }
    1. The hashed values can be generated using auth.computeHash(password, salt) where auth is a JDBCAuth instance. Salt values can also be generated using auth.generateSalt().

    This impacts the MainVerticle class, as we now deploy it first:

    1. JsonObject dbConf = new JsonObject()
    2. .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
    3. .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);
    4. vertx.deployVerticle(new AuthInitializerVerticle(),
    5. new DeploymentOptions().setConfig(dbConf), context.asyncAssertSuccess());
    6. vertx.deployVerticle(new WikiDatabaseVerticle(),